2

We have a webpack application that we're integrating into a site that uses traditional JS scripts, and those scripts define global variables.

Inside our webpack application, we want to import some libraries that happen to already be on the page as scripts. Rather than download the same code twice, once as a script and again embedded inside the webpack bundle, we'd like webpack to not include the code for the library already on the page as a script, but still allow us to use the ES import syntax to "import" the code in our modules, even though the script code in question actually made the library available by a global variable.

So, we have <script src="jquery.js"> on our page. jquery.js supposedly does something like this:

window.jQuery = {};

And in our code compiled by Webpack, we'd like to do:

import jQuery from 'jquery';
jQuery === window.jQuery // true

Is there any way for Webpack to be configured to resolve certain dependencies, like "jquery" in the above example, and determine that it should transform the import code into a reference to that global variable?

The intent here is to gradually opt into the new ES module syntax in new code in our legacy application, while still taking advantage of the fact that the same code is already available on the page as a script.

I checked Webpack's guide on "shimming" but it seems to offer every capability except the one I've described in this post.

Jackson
  • 9,188
  • 6
  • 52
  • 77
  • 3
    This is not a duplicate question. I am asking how to *import* something. The other question is asking how to *exclude* something. The other person's intent and the answer just happened to be the same. – Jackson Oct 07 '17 at 04:31

1 Answers1

5

Use webpack's externals:

Prevent bundling of certain imported packages and instead retrieve these external dependencies at runtime.

externals: {
  jquery: 'jQuery'
}
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • What if I want to mix multiple js together using webpack, and one of them is vuex which define window.Vuex. After importing mixed.js by script tag, in code after it window.Vuex is undefined ? – Jiro Matchonson Nov 03 '22 at 17:48