Webpack 4 migration CommonsChunkPlugin

前端 未结 4 931
傲寒
傲寒 2020-12-02 11:16

I need help migrating the following code from webpack 3 to 4.

new webpack.optimize.CommonsChunkPlugin({
    minChunks: module => module.context &&         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-02 11:50

    I have two entry files and want only the dependencies of the first one to be included in the vendor chunk. The dependencies of the second entry should all stay in its own bundle.

    Assuming your entrypoints are main and secondary:

    entry: {
        main: 'path-to/main.js',
        secondary: 'path-to/secondary.js'
    }
    

    Using webpack-4 You can extract only the vendors modules from main chunk but leave other third parties modules referenced in secondary inside that chunk using the test function of the cacheGroups you want to create.

    optimization: {
        splitChunks: {
            cacheGroups: {
                vendors: {
                    name: 'vendors',
                    chunks: 'all',
                    reuseExistingChunk: true,
                    priority: 1,
                    enforce: true,
                    test(module, chunks) {
                        const name = module.nameForCondition && module.nameForCondition();
                        return chunks.some(chunk => {
                            return chunk.name === 'main' && /[\\/]node_modules[\\/]/.test(name);
                        });
                    }
                },
                secondary: {
                    name: 'secondary',
                    chunks: 'all',
                    priority: 2,
                    enforce: true,
                    test(module, chunks) {
                        return chunks.some(chunk => chunk.name === 'secondary');
                    }
                }
            }
        }
    }
    

提交回复
热议问题