I am trying to set up webpack to build my source code into its own output bundle, and output all node_modules to their own separate vendor file(s). I am using webpack-bundle-analyzer to see what’s happening. Without an optimization
property, I get this kind of output:
// webpack.config.js
module.exports = {
entry: path.resolve(__dirname, "wwwroot", "js", "index.js"),
output: {
path: path.resolve(__dirname, "wwwroot", "dist"),
filename: "[name].bundle.js",
chunkFilename: "[name].bundle.js",
},
cache: {
type: "filesystem",
allowCollectingMemory: true,
},
module: {
rules: [...],
},
};
Gives this output:
You can see the main.bundle.js includes all my src
files (in wwwroot/js
), but it also includes a bunch of code from node_modules, and it blows up the size to 6MB. This is not what I want – main.bundle.js should include only my source code. In this case, main.bundle.js looks like this at a glance:
However, it does work, i.e. the webpage loads with <script src="~/dist/main.bundle.js"></script>
, all the associated modules are pulled in, and everything functions.
Using optimization and chunks: all
Using some optimization
, I can get the bundle to ouput the main.bundle.js with only my source code packed into it, and all the node_modules separate:
// webpack.config.js
module.exports = {
// ... identical to above, plus:
optimization: {
splitChunks: {
chunks: "all",
maxInitialRequests: Infinity,
minSize: 0,
cacheGroups: {
vendor: {
test: /[\/]node_modules[\/]/,
reuseExistingChunk: true,
name(module) {
return module
.identifier()
.split("node_modules")
.reduceRight((item) => item)
.replace(".js", "");
},
},
},
},
},
};
The use of chunks: all
, maxInitialRequests: Infinity
, minSize: 0
is what does just the trick to get me my desired output: my source code only within main.bundle.js, and the node_modules packaged up separately. (That idea came from this question):
My main.bundle.js here is about 500kb, and a quick glimpse of it looks like this:
The problem is, this doesn’t work. The webpack loads, and pulls in main.bundle.js, but it doesn’t seem to ever run. I.e. throwing a console.log('find me')
into my entry of index.js
makes it into the main.bundle.js
, but that code is never executed, even though the script is pulled into the page.
The critical piece seems to be chunks: all
– when I use this, the bundle is split nicely as shown in the second image above, but the code never runs. When I don’t use this, the code is not split nicely between source code and node_modules, but the code does run (regardless of minSize
or maxInitialRequests
.
For good measure I tried chunks: initial
, and while the organization of node modules is a bit different, the result is the same – nice small main.bundle.js
, that doesn’t actually run:
What am I doing wrong that chunks: "all" / "initial"
causes the main
bundle to be pulled into the page, but never run?