avatar

目录
webpak 性能优化(4)tree-shanking&scope-hostig

两个webpack自带的优化:tree-shaking 和 scope-hosting 都是在生产(production)模式下

tree-shaking

在 mode: production 下,使用 import 引入模块,打包时会忽略模块中没有使用的代码

举例:

Javascript
// test.js
let sum = function(a,b){
return a + b + 'sum'
}

let minus = (a, b)=>{
return a-b+'minus'
}

export default {sum, minus}
Javascript
// index.js
import calc from './test.js'

console.log(calc.sum(1,2))

index.js 只使用了 test.js 中的 sum 方法;在开发模式下打包,sum 和 minus 都会被打包,在生产模式下,只打包 sum

如果使用 require 加载,sum 和 minus 都会打包

scope-hosting 变量提升

在生产环境下可以提升作用域

Javascript
let a = 1;
let b = 2;
let c = 3;
let d = a + b + c;
console.log(d);

webpack在生产环境下打包的时候,会直接将 d 打包成 a+b+c 的结果,无需声明多个变量再去相加

文章作者: GRIT
文章链接: https://grit0821.github.io/Blog/2020/02/04/webpak-%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96%EF%BC%884%EF%BC%89tree-shanking-scope-hostig/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Grit's World