10天掌握webpack 4.0 优化篇 (5)抽离公共代码
我們?cè)陂_(kāi)發(fā)多個(gè)頁(yè)面的項(xiàng)目的時(shí)候,有時(shí)候會(huì)在幾個(gè)頁(yè)面中引用某些公共的模塊,這些公共模塊多次被下載會(huì)造成資源浪費(fèi),如果把這些公共模塊抽離出來(lái)只需下載一次之后便緩存起來(lái)了,這樣就可以避免因重復(fù)下載而浪費(fèi)資源
場(chǎng)景:
項(xiàng)目中 有 a.js b.js index.js other.js 文件
index.js 和 other.js 同樣引用了 a.js b.js 并且都使用了第3方庫(kù) 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,//添加權(quán)重
test: /node_modules/,//把這個(gè)目錄下符合下面幾個(gè)條件的庫(kù)抽離出來(lái)
chunks: 'initial',//剛開(kāi)始就要抽離
minSize: 0,//大小大于0字節(jié)的時(shí)候需要抽離出來(lái)
minChunks: 2,//重復(fù)2次使用的時(shí)候需要抽離出來(lái)
}
}
}
},
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,//添加權(quán)重
test: /node_modules/,//把這個(gè)目錄下符合下面幾個(gè)條件的庫(kù)抽離出來(lái)
chunks: 'initial',//剛開(kāi)始就要抽離
minSize: 0,//大小大于0字節(jié)的時(shí)候需要抽離出來(lái)
minChunks: 2,//重復(fù)2次使用的時(shí)候需要抽離出來(lái)
}
}
}
},
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/, // 正則表達(dá)式
rules: [
{
test: /.js?$/,
include: path.join(__dirname, 'src'),
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
"presets": [
"@babel/preset-env",
"@babel/preset-react",
]
}
}
}
]
},
}
抽離第3方庫(kù)需要注意:
這里需要配置權(quán)重 priority,因?yàn)槌殡x的時(shí)候會(huì)執(zhí)行第一個(gè)common配置,入口處看到j(luò)query也被公用了就一起抽離了,不會(huì)再執(zhí)行wendor的配置了,所以加了權(quán)重之后會(huì)先抽離第三方模塊,然后再抽離公共common的,這樣就實(shí)現(xiàn)了第三方和公用的都被抽離了。
打包:
在打包后的common~index~other.js 我們可以看出:
a.js 與 b.js 被抽離了
完整代碼:
https://gitee.com/guangzhou110/ten-days_to_master_webpack4/tree/master/webpack-dev-3
總結(jié)
以上是生活随笔為你收集整理的10天掌握webpack 4.0 优化篇 (5)抽离公共代码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: MongoDB的局域网连接问题
- 下一篇: C++11 序列化库 cereal