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 ?
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.
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',
},
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With