tdc
tdc

Reputation: 5464

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 [email protected]. Here is what I've done so far:

npm install [email protected]

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 )

Upvotes: 3

Views: 963

Answers (1)

Dimitris Karagiannis
Dimitris Karagiannis

Reputation: 9358

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

  • Installing [email protected], throws the following warning: npm WARN deprecated [email protected]: 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 [email protected]

  • I checked the source code of the jquery downloaded with npm install [email protected]. 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.

Upvotes: 2

Related Questions