很多同学应该对它比较陌生,熟悉 rollup 和 webpack2 的同学应该听过
先问一个问题:
对于打包后的文件你关注的是什么?
简单的变量话的压缩技术已经不够了
其实13年就有一篇外文专门介绍了单纯压缩已经远远不够了,稍后我们也会放出原文
它的由来?
最早是 rollup 的作者 Rich Harris 在自己的打包工具中设计的一个特性
It only includes the bits of code your bundle actually needs to run
但是昨天也提到这个概念其实最早是 Dart 开发里面的
在 Twitter 上当时有几种定义:
1、a different name for dead code elimination(消除)
2、the same as using transpiler instead of compiler
它是什么?
按作者的原稿:
和不包含 dead code 相比,更倾向包含 live code.
更通俗一点:
使打包的结构只包含实际用到的 exports
依赖 ES6 模块的静态结构
如果某个导出的部分在其他模块没有调用,就不会输出到打包后的文件中
来看一个 rollup 的例子
有两个文件:
一个主文件 main.js
一个被引入文件 test.js
// test.js
// 导出 2 个方法
export function hello() {
console.log('hello DDFE');
export function say() {
console.log('say');
第一种:
// main.js
// 通过 import 的方式,而且两个方法都调用
import {hello, say} from './test.js';
console.log(hello());
console.log(say());
打包编译后:
function hello() {
console.log('hello DDFE');
function say() {
console.log('say');
console.log(hello());
console.log(say());
第二种:
// main.js
// 通过 import 的方式,但是只调用 hello
import {hello, say} from './test.js';
console.log(hello());
打包编译后:
function hello() {
console.log('hello DDFE');
console.log(hello());
通过比较,我们看到打包结果是不一样的,在主模块别引入的方法才会打包到最终的文件中。
局限:
作者也提到了 rollup 虽然设计了这个特性(采用 top-level AST nodes),但是其实还会包含一些没被使用的代码
当然 rollup 不只是有 tree-shaking