1. 程式人生 > >tree-shaking

tree-shaking

先問一個問題:

對於打包後的檔案你關注的是什麼?

簡單的變數話的壓縮技術已經不夠了

其實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 的例子

有兩個檔案:

  1. 一個主檔案 main.js

  2. 一個被引入檔案 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());

    通過比較,我們看到打包結果是不一樣的,在主模組別引入的方法才會打包到最終的檔案中。