0

大厂喜欢问的TreeShaking到底是啥?好在哪呢?五分钟弄懂!

 1 month ago
source link: https://www.51cto.com/article/784802.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

大厂喜欢问的TreeShaking到底是啥?好在哪呢?五分钟弄懂!

作者:林三心不学挖掘机 2024-03-28 08:43:42
Tree Shaking中文含义是摇树,在webpack中指的是打包时把无用的代码摇掉,以优化打包结果。而webpack5已经自带了这个功能了,当打包环境为production时,默认开启tree-shaking功能。

大家平时在查 webpack构建体积优化 ,可能都会查到 tree-shaking 这个东西,很多人看到这个东西,就会把它背下来,用来应付以后面试官可能会问到的情况。

但是,又有多少人去真的了解一下 tree-shaking 呢?自己去实践一下看 tree-shaking 到底起了哪些作用?对于我们的打包体积的优化又有多少呢?

Tree Shaking中文含义是摇树,在webpack中指的是打包时把无用的代码摇掉,以优化打包结果。

而webpack5已经自带了这个功能了,当打包环境为production时,默认开启tree-shaking功能。

准备两个文件main.js、util.js

  • util.js
function a () {
  console.log('a')
}
function b () {
  console.log('b')
}
export default {
  a, b
}
  • main.js
import a from './util'

// 使用a变量,调用文件里面的a函数,不使用b函数
console.log(a.a())
console.log('hello world')

// 不可能执行的代码
if (false) {
  console.log('haha')
}

// 定义了但是没用的变量
const m = 1

前面说了webpack5在环境production下打包的话,默认开启tree-shaking,那我们运行npm run build进行一下打包,看看打包后的代码长啥样:

(()=>{"use strict";
const o=function(){console.log("a")};
console.log(o())
console.log("hello world")}
)();

结论:可以看到打包后,把b函数、不可能执行的代码、定义未用的变量通通都剔除了,这在一个项目中,能减少很多的代码量,进而减少打包后的文件体积。

sideEffects

先来讲讲一个东西——副作用,是什么东西呢?副作用指的是:除了导出成员之外所做的事情,我举个例子,下面的a.js是没副作用的,b.js是有副作用的:

function console () {
  console.log('console')
}
export default {
  console
}
function console () {
  console.log('console')
}

// 这个就是副作用,会影响全局的数组
Array.prototype.func = () => {}

export default {
  console
}

有无副作用的判断,可以决定tree-shaking的优化程度,举个例子:

  • 我现在引入a.js但是我不用他的console函数,那么在优化阶段我完全可以不打包a.js这个文件。
  • 我现在引入b.js但是我不用他的console函数,但是我不可以不打包b.js这个文件,因为他有副作用,不能不打包。

sideEffects的使用

sideEffects可以在package.json中设置:

// 所有文件都有副作用,全都不可 tree-shaking
{
 "sideEffects": true
}
// 没有文件有副作用,全都可以 tree-shaking
{
 "sideEffects": false
}
// 只有这些文件有副作用,
// 所有其他文件都可以 tree-shaking,
// 但会保留这些文件
{
 "sideEffects": [
  "./src/file1.js",
  "./src/file2.js"
 ]
}

当我把sideEffects设置成true之后,整个打包体积增加了100k,说明默认的false还是有用的。

责任编辑:武晓燕 来源: 前端之神

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK