I am currently experimenting with code splitting in Webback4.
I'd like to put every external package (from node_modules) into its own chunk. Can someone please provide me a hint how to do it?
This is how far I got so far (except from webpack.config.js)
optimization: {
runtimeChunk: {
name: "runtime"
},
splitChunks: {
chunks: "all",
name(module) {
return module.resource && module.resource.replace(/\//g, "_");
}
}
}
But now, every single JS file is a separate chunk. So, I'd like to do it per package.
Ideally, the filename should be of form:
<package-name>-<version>.js
for example:
protobufjs-6.1.3.js
Help?
Bonus: could I also somehow generate content hash for the filename?
How about this:
const path = require('path');
const webpack = require('webpack');
module.exports = {
entry: path.resolve(__dirname, 'src/index.js'),
plugins: [
new webpack.HashedModuleIdsPlugin(), // so that file hashes don't change unexpectedly
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: '[name].[contenthash].js',
},
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
// get the name. E.g. node_modules/packageName/not/this/part.js
// or node_modules/packageName
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
// npm package names are URL-safe, but some servers don't like @ symbols
return `npm.${packageName.replace('@', '')}`;
},
},
},
},
},
};
You can further explanation of this in the following article: https://medium.com/hackernoon/the-100-correct-way-to-split-your-chunks-with-webpack-f8a9df5b7758
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