Read more

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

Emanuel
May 08, 2019Software engineer at makandra GmbH

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

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
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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:

import jQuery from 'jquery'

window.$ = jQuery
window.jQuery = jQuery

In the browser jQuery will be undefined, whereas $ is still defined. The issue Show archive.org snapshot 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).

import jQuery from 'jquery'

global.$ = jQuery
global.jQuery = jQuery
Posted by Emanuel to makandra dev (2019-05-08 09:59)