The global variable is not defined after Splitchunks

153 views Asked by At

I'm applying the SplitChunksPlugin of webpack into my service.

Like,

...
optimization: {
  splitChunks: {
    chunks: 'all'
  }
}

And some issues came up. Before talking about the issues, I'll tell the minified structure of my service.

  1. The web service brings serveral script. For example,
<script crossorigin type="module" src="/js/global.[chunkhash].js"></script>
<script crossorigin type="module" src="/js/main.[chunkhash].js"></script>

(I'm using menifest.json)

  1. The global.js is like
import _ from 'lodash';

Object.assign(window, { _ });
  1. The main.js is like
... other codes

_.add(10, 20); // using lodash that is assigned globally in global.js

That's it. The real structure is more complicated. So, now is the issue.

  1. When I do not use the splitChunks or set splitChunks.chunks to async, there is no issue. But when I set the splitChunks.chunks to all, the following issue is shown in browser.
_ is not defined

And if I type _ in browser's console, _ exists.

  1. So, to find what happen, I insert console.log into global.js like
import _ from 'lodash';

Object.assign(window, { _ });

console.log(_, window);

The console.log shows the log when splitChunks.chunks = 'async' but do not when splitChunks.chunks = 'all'.

  1. Now, I try to import all vendors like
/* vendors */
<script type="text/javascript" src="/js/vendors~global.[chunkhash].js"></script>
<script type="text/javascript" src="/js/vendors~main~otherjs.[chunkhash].js"></script>
/* // vendors */
<script crossorigin type="module" src="/js/global.[chunkhash].js"></script>
<script crossorigin type="module" src="/js/main.[chunkhash].js"></script>

The html has above lines, but when I see the network tab in devtool, there is no vendors javascript files.

I struggle to how to apply the splitChunksPlugin but it is not easy... and I could not find a little clue...

It will be big help for any answer or idea ! Thanks.

0

There are 0 answers