webpack之SplitChunksPlugin
阿新 • • 發佈:2021-01-02
使用 SplitChunksPlugin 提取 chunks 中的公共程式碼,生成新的 chunk
-
chunk 的三種情況
- 專案入口 entry
- 通過import()動態引入的程式碼
- 通過 splitChunks 拆分出來的程式碼
-
splitChunks 預設配置(部分)
module.exports = {
//...
optimization: {
splitChunks: {
chunks: 'async', // chunk 類別, async 查動態匯入模組(import),all 查全部,initial - 非動態
minSize: 20000, // 最小大小
minChunks: 1, // 最小引用數
automaticNameDelimiter: '~', // 生成 chunk 檔名中的連線符
cacheGroups: { // 繼承或重寫 splitChunks.*
defaultVendors: { // cacheGroups 名
test: /[\\/]node_modules[\\/]/, // 檔案過濾,省略查詢所有模組
priority: -10, // 權重
},
default: { //
minChunks: 2,
priority: -20,
}
}
}
}
};
多專案入口提取 公共chunk
// a.js
import './helpers.js'
// b.js
import './helpers.js'
// helpers.js
console.log('helpers')
module.exports = {
// ...
entry: {
a: path.resolve(__dirname, './src/a.js'),
b: path.resolve(__dirname, './src/b.js' )
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]_[chunkhash:8].js'
},
optimization: {
splitChunks: {
cacheGroups: { // 繼承或重寫 splitChunks.*
default: {
name: 'common', // chunk 名稱
chunks: 'initial', // chunk 類別
minSize: 0, // 最小大小
minChunks: 2,
priority: -20,
}
}
}
}
}
node_modules 提取 chunk
// a.js
import './helpers.js'
// helpers.js
console.log('helpers')
import _ from 'lodash'
console.log(_.join(['Hello', 'webpack'], ' '));
module.exports = {
entry: {
a: path.resolve(__dirname, './src/a.js'),
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]_[chunkhash:8].js'
},
optimization: {
splitChunks: {
cacheGroups: { // 繼承或重寫 splitChunks.*
defaultVendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'initial', // chunk 類別
name: 'vendors'
},
}
}
}
}
開箱即用的 splitChunks (使用預設值)
- 動態匯入,使用 lodash 依賴,生成兩個 chunk
// a.js
import(/* webpackChunkName: "helpers" */'./helpers')
// helpers.js
console.log('helpers')
import _ from 'lodash'
console.log(_.join(['Hello', 'webpack'], ' '));