This plugin generates module ID from unique hashes based on the file contents of the module. Unlike Webpack's HashedModuleIdsPlugin, which generates hashes from the relative import path of the module.
You can use this plugin to guarantee that multiple webpack bundles on a page do not clash their module IDs and overwrite modules when loading chunk assets. This is pivotal to achieving long-term caching across disparate builds.
Furthermore, this plugin gives you the ability to share chunks between multiple webpack bundles on a page so long as they use the same versions, and when they do not, the page will load both and continue working as expected.
npm i -D content-hashed-module-ids-webpack-plugin
This plugin takes the same options used by Webpack's HashedModuleIdsPlugin.
webpack.config.js
const ContentHashedModuleIdsPlugin = require('content-hashed-module-ids-webpack-plugin');
module.exports = {
// ...
plugins: [
new ContentHashedModuleIdsPlugin({
// HashedModuleIdsPlugin options
})
]
// ...
}
This configuration is heavily based on the article The 100% correct way to split your chunks with webpack.
const ContentHashedModuleIdsPlugin = require('content-hashed-module-ids-webpack-plugin');
const isDev = process.env.NODE_ENV !== 'production';
module.exports = {
context: __dirname,
entry: path.resolve(__dirname, './index.js'),
output: {
filename: '[name].[chunkhash].js',
path: path.join(__dirname, './dist'),
publicPath: './static/',
library: 'SharedChunkBundles' // Groups all similarly built packages into the same library
},
plugins: [
new ContentHashedModuleIdsPlugin() // Guarantees that all moduleIds under the SharedChunkBundles library are unique
],
optimization: {
runtimeChunk: 'single',
splitChunks: {
chunks: 'all',
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendors: {
// splits out all node_modules into chunks by name
test: /[\\/]node_modules[\\/]/,
name: (module) => {
const pName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `npm.${pName.replace('@', '')}`;
}
}
}
}
},
mode: isDev ? 'development' : 'production',
devtool: isDev ? 'eval' : undefined,
}