webpack: 從指定入口文件中提取公共文件

在不明白CommonsChunkPlugin的使用狀況下,直接上手webpack4的splitChunks,實在是難上加難。爲了能更好的理解splitChunks的使用,必須出個題目,練練手,才能從中有所收穫(下面的題目不考慮實際應用場景):webpack

從指定入口文件中提取公共文件

CommonsChunkPlugin的實現:

entry: {
        index:'./src/index.js',
        index1:'./src/index1.js',
        index2:'./src/index2.js'
},
plugins: [
    new CommonsChunkPlugin({
        name:"common1",
        chunks:['index','index1','index2']
    })
]

其中index和index1以及index2都是打包的入口文件。web

splitChunks的實現:

optimization: {
        splitChunks: {
            chunks:"all",
            minSize: 0,
            cacheGroups: {
                common: {
                    minChunks: 3,
                    priority: -1,
                    name:'common',
                    chunks (chunk) {
                        // exclude `my-excluded-chunk`
                        return ['index','index1','index2'].includes(chunk.name);
                    }
                }
            }
        }
    }

在cacheGroups下面咱們定義了一個common。經過chunks函數,指定三個入口文件爲:'index','index1','index2',同時咱們還要設置minChunks爲3,表示指定三個入口文件中提取出的公共文件,最少要被三個不一樣的入口文件引用。因此就是從三個入口文件中提取公共的文件。app

從兩個公共文件中,再提取公共部分

先說一下,這是什麼意思:函數

  1. 有6個公共文件a,b,c,d,e,f。
  2. 從a,b,c中提取其公共的部分x,從d,e,f中也提取公共部分y。
  3. 從x,y中再提取公共部分z。

下面給出webpack3 和webpack4下的處理code

CommonsChunkPlugin的實現:

new CommonsChunkPlugin({
    name:"common1",
    chunks:['index','index1','index2']
}),
new CommonsChunkPlugin({
    name:"common2",
    chunks:['app','app1','app2']
}),
new CommonsChunkPlugin({
    name:"common3",
    chunks:['common1','common2']
})

很清楚,先從'index','index1','index2'中提取公共文件‘common1’,再從'app','app1','app2'中提取公共文件‘common2’。最後從‘common1’和‘common2’中再提取出公共文件common3。webpack4

splitChunks的實現:

optimization: {
        runtimeChunk: 'single',
        splitChunks: {
            chunks:"all",
            minSize: 0,
            cacheGroups: {
                common3: {
                  minChunks: 6,
                  priority: 1,
                  reuseExistingChunk: true
                },
                common2: {
                    minChunks: 3,
                    priority: -2,
                    name:'common2',
                    chunks (chunk) {
                        // exclude `my-excluded-chunk`
                        return ['app','app1','app2'].includes(chunk.name);
                    }

                },
                common1: {
                    priority: -1,
                    name: 'common1',
                    minChunks: 3,
                    enforce: true,
                    chunks (chunk) {
                        return ['index','index1','index2'].includes(chunk.name);
                    }
                }
            }
        }
    }

我沒有從文檔中找到:提取公共文件以後再處理的方法。因此我用了另一種方式:文檔

  1. 先從6個文件中提取出公共的文件,即common3(common1和common2的公共文件)。
  2. 從'index','index1','index2'中提取common1
  3. 從'app','app1','app2'中提取common2
相關文章
相關標籤/搜索