全部的代碼及筆記都可以在我的github上查看, 歡迎star:https://github.com/Jasonwang911/webpackStudyInit/tree/master/commonThunk
1. 提取公用代碼的作用:
減少代碼的冗余
提高用戶的加載速度
單頁面減少下載,多頁面可以使用緩存
2. webpack3.0 中的 commonsChunkPlugin 插件
webpack的內置插件 webpack.optimize.CommonsChunkPlugin
配置項:
options.name / options.names thunk的名稱
options.filename 打包后的文件名稱
options.minChunks 公用的次數(多少次會被提取): 可以是數字、函數和
options.chunks 指定提取代碼的范圍
options.children
options.deepChildren 是否在子模塊看中繼續提取公用代碼
options.async 創建一個異步的公共代碼塊
3. 不同場景的配置
單頁應用:
多頁應用:
多頁應用+第三方依賴+webpack生成代碼
4. 安裝環境
npm install webpack --save-dev
5. webpack4.0 webpack4 最大的改動就是廢除了CommonsChunkPlugin 引入了 optimization.splitChunks
如果你再webpack4中使用了weppack3的CommonsChunkPlugin 會出現以下報錯: (運行配置文件 webpack3.config.js)
Error: webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks
webpack3.config.js:
var webpack = require('webpack')
var path = require('path')
module.exports = {
mode: 'development',
entry: {
'pageA': './src/pageA'
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].bundle.js',
chunkFilename: '[name].chunk.js'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: 'common',
minChunk: 2
})
],
devtool: 'source-map',
}
webpack4 配置更加簡單,如果設置了 mode 為 production,那么webpack4 會自動開啟 Code Splitting
6. webpack4內置的代碼分割策略
a. 新的chunk是否被共享或者來自node_module的模塊
b. 新的chunk體積在壓縮之前是否大於30kb
c. 按需加載chunk的並發請求數量小於等於5個
d. 頁面初始加載時的並發請求數量小於等於3個
7. 合理使用 Code Splitting
a. 基礎類庫 chunk-libs : 比如 vue + vuex + vue-router + axios 這類的全家桶,一旦立項升級頻率不高,但是每個文件基本都需要依賴
b. UI組件庫 chunk-common : 比如 element-ui 升級頻率也不會高,單獨打包原因是體積比較大
c. 低頻組件 : 比如一些特定頁面需要使用的第三方庫文件--富文本編輯器等
d. 公用業務代碼 : 比如vue的路由懶加載 component: () => import('./xxx.vue') webpack默認會將其打包成一個獨立的bundle
針對如上需求可進行如下配置:
splitChunks: {
chunks: "all",
cacheGroups: {
libs: {
name: "chunk-libs",
test: /[\/]node_modules[\/]/,
priority: 10,
chunks: "initial" // 只打包初始時依賴的第三方
},
elementUI: {
name: "chunk-elementUI", // 單獨將 elementUI 拆包
priority: 20, // 權重要大於 libs 和 app 不然會被打包進 libs 或者 app
test: /[\/]node_modules[\/]element-ui[\/]/
},
commons: {
name: "chunk-comomns",
test: resolve("src/components"), // 可自定義拓展你的規則
minChunks: 2, // 最小共用次數
priority: 5,
reuseExistingChunk: true
}
}
};
