Skip to content

tree shaking ​

2022-11-15 09:07:56

什么是 tree shaking ​

字面翻译:摇晃树,当然肯定不是这个意思,tree shaking 是基于 ES Module 进行静态分析,通过 AST 将用不到的函数进行移除,把没有使用到的代码在打包的时候去掉,从而减少打包体积

比如这里我们从 math 中引入了两个函数,但是只使用了 add 函数,sub 并没有使用,这时 tree shaking 就会发挥作用,在打包时 sub 并不会被打包进来

js
import { add, sub } from '@/utils/math'

add(1, 2)

打包后的代码

js
function add(a, b) {
  return a + b
}

add(1, 2)

Released under the MIT License.