Reputation: 2353
Configuring webpack I was wondering something for the optimization. I have two JS files index.js and helper.js. I import helper.js in index.js like that:
import * as helper from 'helper.js';
In these two JS files, I import some node_modules.
Regarding this, to prevent duplication code and caching you can do that:
const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
index: './src/index.js'
},
output: {
filename: '[name].[contenthash].js',
path: path.resolve(__dirname, 'dist')
},
optimization: {
runtimeChunk: 'single',
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
}
};
If I understand well for the optimization, it's only created one vendor file from the folder node_modules ? It will import everything from the folder node_modules even if I don't use everything (for example the devDependencies) ?
Does it take in account the import of helper.js done in index.js in the vendor ?
Why do they use runtimeChunk in the link provided ?
Or should I do just something like that:
optimization: {
splitChunks: {
chunks: 'all'
}
}
Hope you could help me
Upvotes: 1
Views: 556
Reputation: 66435
You don't need the test
as it defaults to node_modules. It will only compile the ones you use. Remember to include that file first before your app one(s) when including them from your html.
It will split all vendor modules out regardless of what file they are included from.
It's worth noting though that since you're importing helper.js into index.js and creating one bundle, webpack will already not duplicate the node_modules but share them, so long as helper.js is not a third party module compiled as a non-es6 module.
In other words webpack will automatically tree shake stuff in your own source files, and es2016 modules in node_modules (not CJS/UMD modules which is the most common).
You only need to split to a vendor bundle if:
a) Your vendor bundle changes with a lot less frequency than your src code (not that common if you're often running npm update
)
b) You're producing multiple output files and you want them to share vendor.js / you don't want to declare them as external and make the consumer install them (e.g. a library of components)
P.S. Not exactly sure what runtimeChunk
is for but personally I would not specify it (leave it as default) unless you have a good reason.
Upvotes: 2