10天掌握webpack 4.0 优化篇 (5)抽离公共代码
生活随笔
收集整理的這篇文章主要介紹了
10天掌握webpack 4.0 优化篇 (5)抽离公共代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
我們在開發多個頁面的項目的時候,有時候會在幾個頁面中引用某些公共的模塊,這些公共模塊多次被下載會造成資源浪費,如果把這些公共模塊抽離出來只需下載一次之后便緩存起來了,這樣就可以避免因重復下載而浪費資源
場景:
項目中 有 a.js b.js index.js other.js 文件
index.js 和 other.js 同樣引用了 a.js b.js 并且都使用了第3方庫 jquery
代碼如下:
a.js
console.log('a' + '--------')
b.js
console.log('b' + '--------')
index.js
import './a'
import './b'
console.log('index.js')
import $ from 'jquery'
console.log($)
other.js
import './a'
import './b'
console.log('other.js')
import $ from 'jquery'
console.log($)
配置webpack.config.js文件
optimization: {
//分割代碼快
splitChunks: {
// 緩存組
cacheGroups: {
// 公共模塊
common: {
chunks: 'initial',
minSize: 0,
minChunks: 2
},
vendor: {
priority: 1,//添加權重
test: /node_modules/,//把這個目錄下符合下面幾個條件的庫抽離出來
chunks: 'initial',//剛開始就要抽離
minSize: 0,//大小大于0字節的時候需要抽離出來
minChunks: 2,//重復2次使用的時候需要抽離出來
}
}
}
},
const path = require('path')
let webpack = require('webpack')
let htmlWebpckPlugin = require('html-webpack-plugin')
module.exports = {
mode: 'production',
optimization: {
//分割代碼快
splitChunks: {
// 緩存組
cacheGroups: {
// 公共模塊
common: {
chunks: 'initial',
minSize: 0,
minChunks: 2
},
vendor: {
priority: 1,//添加權重
test: /node_modules/,//把這個目錄下符合下面幾個條件的庫抽離出來
chunks: 'initial',//剛開始就要抽離
minSize: 0,//大小大于0字節的時候需要抽離出來
minChunks: 2,//重復2次使用的時候需要抽離出來
}
}
}
},
entry: {
index: './src/index.js',
other: './src/other.js',
},
output: {
filename: '[name].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new htmlWebpckPlugin({
template: './public/index.html'
}),
new webpack.IgnorePlugin(/^./locale/, /moment$/)
],
module: {
noParse: /jquery|lodash/, // 正則表達式
rules: [
{
test: /.js?$/,
include: path.join(__dirname, 'src'),
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
"presets": [
"@babel/preset-env",
"@babel/preset-react",
]
}
}
}
]
},
}
抽離第3方庫需要注意:
這里需要配置權重 priority,因為抽離的時候會執行第一個common配置,入口處看到jquery也被公用了就一起抽離了,不會再執行wendor的配置了,所以加了權重之后會先抽離第三方模塊,然后再抽離公共common的,這樣就實現了第三方和公用的都被抽離了。
打包:
在打包后的common~index~other.js 我們可以看出:
a.js 與 b.js 被抽離了
完整代碼:
https://gitee.com/guangzhou110/ten-days_to_master_webpack4/tree/master/webpack-dev-3
總結
以上是生活随笔為你收集整理的10天掌握webpack 4.0 优化篇 (5)抽离公共代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MongoDB的局域网连接问题
- 下一篇: C++11 序列化库 cereal