Glenn Mohammad
Glenn Mohammad

Reputation: 4683

webpack - imports-loader and ProvidePlugin: similar but not the same?

Here is what I have:

a.js

$(() => {
  $.x = 42;
  console.log('hello from a');
});

b.js

$(() => {
  console.log($.x);
  console.log('hello from b');
});

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="/vendor.js"></script>
<script src="/a.js"></script>
<script src="/b.js"></script>

My question is, do both webpack configurations below achieve exactly the same result?

[1] webpack.config.js (with imports-loader)

const config = {
  entry: {
    a: './a.js',
    b: './b.js',
    vendor: [
      'jquery',
    ],
  },
  module: {
    rules: [
      {
        test: /(a|b)\.js$/,
        use: 'imports-loader?$=jquery',
      },
    ],
  },
};

[2] webpack.config.js (with ProvidePlugin)

const config = {
  entry: {
    a: './a.js',
    b: './b.js',
    vendor: [
      'jquery',
    ],
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
    }),
  ],
};

If they are similar but not the same, when to use one over another then?

Furthermore, in b.js, $.x is equal to undefined, does this mean $ refers to different jQuery objects? If so, how do I make them to refer to the same (global) jQuery instance?

Upvotes: 2

Views: 595

Answers (1)

Quotidian
Quotidian

Reputation: 2940

The imports-loader only pulls in the import when the parent loader is run. (In your case, only on js files.) The imported file is "attached" to the parent.

The ProviderPlugin imports into the "global" namespace, making whatever you import available wherever. It's typically used for stand alone libraries like jquery.

Similar, but not the same.

Upvotes: 1

Related Questions