在項目開發(fā)中筋粗,可能會遇到這樣的問題,就是一個方法庫敦间,我們只用了其中的一兩個方法瓶逃,但是打包的時候還是會把所有的方法都打包進(jìn)去了。這明顯是不合理的廓块,怎么辦呢厢绝?
下面給大家介紹webpack的tree shaking就是來解決這些問題的。
先來說說什么是tree shaking带猴?
在webpack中一般有一個入口文件昔汉,像一個樹一樣,入口文件有很多依賴的模塊拴清,這些模塊就像是樹干靶病。而tree shaking則是要把這棵樹上多余的,用不到的方法給搖掉口予,其實就是去除用不到的方法娄周,變量,起到優(yōu)化的作用沪停,特別是有第三方依賴的時候煤辨。
我們先看一個簡單的demo。
//A.js
function methosA() {
console.log('this is methosA')
}
function methosB() {
console.log('this is methosB')
}
function methosC() {
console.log('this is methosC')
}
function methosD() {
console.log('this is methosD')
}
function methosE() {
console.log('this is methosE')
}
export {
methosA,
methosB
}
import { methosA } from './methods/A'
if(false) {
console.log('this is need delete code')
}
console.log(methosA())
//webpack.config.js
const path = require('path')
module.exports = {
entry: {
app: path.join(__dirname, 'src/app.js')
},
output: {
filename: '[name].bundle.js',
path: path.join(__dirname, 'dist')
}
}
如果是webpack3的版本木张,打包之后是會把A.js中的所有文件都打包進(jìn)去众辨,所以tree-sharking需要借助插件。
如果是webpack4版本舷礼,自動會進(jìn)行壓縮和打包鹃彻。
那么如果有第三方插件怎么辦呢?
import { methosA } from './methods/A'
import { chunk } from 'lodash'
console.log(chunk([1,2,3,4,5,6,7],2))
if(false) {
console.log('this is need delete code')
}
console.log(methosA())
比如我引入了lodash這個第三方模塊妻献,我們打包看看浮声。
我們只用了一個方法,不可能會有這么大的文件旋奢,所以打包是失敗的泳挥。
我們再加上插件(webpack中的新插件UglifyjsWebpackPlugin)
plugins: [
new UglifyJsPlugin()
]
再次打包也還是不行,這是為什么呢至朗?
這需要講幾句tree-sharking的原理屉符,tree-sharking是靜態(tài)的去分析代碼,而ES6模塊依賴關(guān)系是確定的,和運行時的狀態(tài)無關(guān)矗钟,可以進(jìn)行可靠的靜態(tài)分析唆香,這就是tree-shaking的基礎(chǔ)。(https://juejin.im/post/5a4dc842518825698e7279a9 一篇介紹tree-shaking原理的文章)
而很多的第三方為了考慮兼容性吨艇,代碼都是通過babel編譯過的語法躬它。所以我們可以找一下這個第三方庫的es版本。
import { methosA } from './methods/A'
import { chunk } from 'lodash-es'
console.log(chunk([1,2,3,4,5,6,7],2))
if(false) {
console.log('this is need delete code')
}
console.log(methosA())
再執(zhí)行以下打包东涡。
注(webpack還有一個插件babel-minify-webpack-plugin冯吓,集合了babel和uglify,也可以用來tree-sharking)
下面說說css的tree-shaking
css的tree-shaking也很簡單,只要用一個插件(purifycss-webpack)疮跑,就能自動幫我們做tree-shaking.
在npm上有明確的用法
這里就不演示了组贺。