Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modules evaluated multiple times with CommonChunk plugin in webpack

I have a webpack build with multiple entries and one common chunk. Sometime I load entry1 sometimes I load entry1 and entry2, sometimes entries 2 and 3. In any case I always include the common chunk.

Everything seems fine, the bundled files are fine. But it seems there is a problem at runtime. When I need two entries and they both depend on some module (that is in the common file). This module is evaluated twice.

Simple example:

entry1.js

require('./dep.js');

entry2.js

require('./dep.js');

deps.js

alert('called')
module.exports = 2;

Here I see the alert called twice. I was expecting webpack to do something similar as node.js and cache the require.

I double checked and the content of deps.js is indeed in the common.js file and by placing a breakpoint on the alert shows that the same code is called multiple times. Which is not expected.

Is there a way to solve this ?

like image 915
DARK_DUCK Avatar asked Nov 01 '25 06:11

DARK_DUCK


2 Answers

If this is webpack 4, you should use optimization.runtimeChunk: 'single` just like suggested in the documentation. Otherwise modules are initialized every time as per the docs:

Imported modules are initialized for each runtime chunk separately, so if you include multiple entry points on a page, beware of this behavior. You will probably want to set it to single or use another configuration that allows you to only have one runtime instance.

like image 52
Herz3h Avatar answered Nov 04 '25 10:11

Herz3h


I had the same problem with vue cli MPA (multi page app)

I solved by adding 'runtime' to the list of chunks of each page in addition to the solution given by @Herz3h

Here is what vue.config.js should look like

module.exports = {
  pages: {
    page1: {
      entry: 'src/pages/1/main.js',
      chunks: [
        'chunk-vendors',
        'chunk-common',
        'runtime', //Make sure you add this in your chunks
        'page1',
      ]
    }
  },
  configureWebpack() {
    return {
      optimization: {
        runtimeChunk: 'single',
      },
    }
  }
}
like image 41
Tofandel Avatar answered Nov 04 '25 10:11

Tofandel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!