拿 lodash 做个实验 ,如何引用才能利用treeShaking
测试
1. import _ from 'lodash-es'
import _ from 'lodash-es'
const testObj = {
a:{
b:{
c:'xxx'
}
}
}
const res = _.cloneDeep(testObj)
console.log(res)
// 结果 × 82kb
2. import * as _ from 'lodash-es'
import * as _ from 'lodash-es'
const testObj = {
a:{
b:{
c:'xxx'
}
}
}
const res = _.cloneDeep(testObj)
console.log(res)
// 结果 √ 14kb
3. import {cloneDeep} from 'lodash-es'
import {cloneDeep} from 'lodash-es'
const testObj = {
a:{
b:{
c:'xxx'
}
}
}
const res = cloneDeep(testObj)
console.log(res)
// 结果 √ 14kb
4. import {cloneDeep} from 'lodash'
import {cloneDeep} from 'lodash'
const testObj = {
a:{
b:{
c:'xxx'
}
}
}
const res = cloneDeep(testObj)
console.log(res)
// 结果 × 70kb
5. import cloneDeep from 'lodash/cloneDeep'
const testObj = {
a:{
b:{
c:'xxx'
}
}
}
const res = cloneDeep(testObj)
console.log(res)
// 结果 × 17kb
6. import cloneDeep from 'lodash-es/cloneDeep'
const testObj = {
a:{
b:{
c:'xxx'
}
}
}
const res = cloneDeep(testObj)
console.log(res)
// 结果 × 14kb
结论
- 使用 es版本
- 使用
import * as xxx from 'xxx'可被 treeShaking 且方便引用
原理 Webpack 官网提到,要开启模块的 Tree-shaking,需要满足以下四个条件:
- 使用 ES6 的 import export 语句
- 确保 ES6 模块没有被 babel 等编译器转换成 ES5 CommonJS 的形式
- 项目 package.json 文件中,要有 "sideEffects" 属性的定义(false 表示所有文件无副作用,可启用 Tree Shaking)
- 使用 Webpack 的 production mode
根据以上说明可知 必须使用 es版本
但是使用 es 版本 import _ from 'lodash-es' 不能被优化,因为导入了 export default 整个对象
export default 对象被 import 后,挂在 default 上的属性和方法,即使没有被调用,也无法被 tree-shaking。 所以我们在组织模块文件时,应当尽可能避免 export default {A, B, C} 的写法