Posted 2 months ago. Visible to the public.

Webpacker: Side effects of using window.* within the ProvidePlugin

Some older Node modules rely on window.jQuery to be present. One suggested solution is to use this config in the app/config/webpack/environment.js:

Copy
const { environment } = require('@rails/webpacker') const webpack = require('webpack') environment.plugins.prepend( 'Provide', new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery' }) ) module.exports = environment

This will work. But a side effect is that the following approach in the app/javascript/packs/application.js to expose jQuery to the browser window object will not work anymore:

Copy
import jQuery from 'jquery' window.$ = jQuery window.jQuery = jQuery

In the browser jQuery will be undefined, whereas $ is still defined. The issue is known (here $ is undefined as "window.jQuery": "jquery" is used).

You can use global instead of window, which will solve the issue (Webpack will transform global to window in the context of a web application).

Copy
import jQuery from 'jquery' global.$ = jQuery global.jQuery = jQuery

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Emanuel De
Last edit:
about 1 month ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more