Prefix Prefix - 1 month ago 10
jQuery Question

Webpack make jQuery globally available during development

I'm writing a react app that will live inside of a webpage that already contains jquery. This means I need global access to jQuery during development, but do not want to include it with the bundle on build ( since jquery will already exist on the page where it is deployed ).

I'm having difficulty getting jquery as a global ( aka accessible from anywhere via

$
or
window.jquery
) to work. Specifically I need jQuery@1.7.2. Here is what I've done so far:

npm install jquery@1.7.2


then, in webpack.dev.config.js:

plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
})
]


...however, when I run my dev server (
webpack-dev-server
) and try to use jQuery in a module, I get:

error '$' is not defined


Any ideas? my main goals are:


  1. should be present during development build, but not bundled for production

  2. should be globally accessible from any component via the window object

  3. not have to explicitly be imported into each module ( assume it's a global )


Answer

After spending some time on this, here are my observations:

  • Installing jquery@1.7.2, throws the following warning: npm WARN deprecated jquery@1.7.2: Versions of the jquery npm package older than 1.9.0 are patched versions that don't work in web browsers. Please upgrade to >=1.11.0..

  • Trying to build my bundles using this version of jquery completely fails. I don't know how you did it, but for me it fails. I am using webpack@1.13.3

  • I checked the source code of the jquery downloaded with npm install jquery@1.7.2. It is definitely modified from the original source. The original source code still exists though under jquery/tmp/jquery.js

Conclusion

Your best bet for this to work is by doing this, at some point before the rest of your code:

import 'jquery/tmp/jquery'.

This way the file will be executed, jquery will be registered to window, as originally intended, and you can use $ in the rest of your code.

Comments