The use of optimization.splitChunks in webpack

recently in learning webpack4, I don"t know much about the newly added optimization. I wrote a demo, according to online learning, but I didn"t expect the result. Ask God for help to see what the problem is

.

package.json:

{
    "name": "test",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "webpack": "^4.15.1",
        "webpack-cli": "^3.1.0"
    },
    "dependencies": {
        "lodash": "^4.17.10"
    }
}

module.js:

export default "module";

subPageA.js:

import "./module.js";
export default "subPageA";

subPageB.js:

import "./module.js";
export default "subPageB";

pageA.js:

import "./subPageA.js";
import "./subPageB.js";

import * as _ from "lodash";
console.log("At page "A" :", _);

export default "pageA";

pageB.js:

import "./subPageA.js";
import "./subPageB.js";

import * as _ from "lodash";
console.log("At page "B" :", _);

export default "pageB";

webpack.config.js:

const path = require("path");
const webpack = require("webpack");

module.exports = {
    entry: {
        pageA: "./src/pageA.js",
        pageB: "./src/pageB.js"
    },
    output: {
        filename: "[name].bundle.js",
        path: path.resolve(__dirname, "dist"),
        chunkFilename: "[name].chunk.js"
    },
    optimization: {
        splitChunks: {
            cacheGroups: { 
                commons: {
                    name: "commons",
                    chunks: "all", 
                    minChunks: 2,
                    priority: 0 
                },
                vendor: { 
                    name: "vendor",
                    test: /[\\/]node_modules[\\/]/,
                    chunks: "all", 
                    priority: 10 
                }
            }
        }
    }
};
The expected result of

is to generate a commons.chunk.js, that contains repeatedly introduced custom modules, and a vendor.chunk.js module that contains node_modules, that is, the lodash module, but the actual generation is:

what is wrong with my configuration or misunderstanding? (minChunks is set to 1 or 2 to all or other values have been tried, and the result is the same)

Apr.21,2021

original author to answer:
optimization.splitChunks.cacheGroups.common configuration item, is minSize set to 1. There is no minChunks attribute.

Welcome to the original blog to ask questions (the answer will be more detailed). The original blog tutorial will be updated faster.

original address
more tutorial addresses


the answer is wrong

both of your pages have introduced lodash, which is a library in nodemodules, so vender and common conflict
, but you set priority: 10 for vender, so vender has a high priority, so there is only vender without common

after packaging.
Menu