Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

A Rollup from 0 to 1 overhand front-end component library development | tree – shaking mechanism

The above review

  • Rollup from 0 to 1 to fit the front-end component library development | started
  • A Rollup from 0 to 1 overhand front-end component library development | module builds

Tree – shaking concept

In the WebPack project, there is an entry file, which is equivalent to the trunk of a tree, and an entry file has many dependent modules, which are equivalent to branches. In reality, you rely on a module but only use some of its functionality. Tree-shaking is a way to remove useless code by shaking off unused modules.

In field

Write your own module

  • cd src
  • touch plugin.js
const a = 1
const b = 2

function random() {
    console.log('random')}export default {
    a,
    b,
    random
}


Copy the code
  • vim index.js
import * as data from './plugin'

console.log(data.default.random, data.default.a, data.default.b)

export default random
Copy the code
  • throughnpx babel-node ./src/index.jsViewing the Running result
> [Function: random] 1 2
Copy the code
  • View packaging resultsdist/payfun.rollbear.dev.es.js
const a = 1;
const b = 2;

function random() {
    console.log('random');
}

var plugin = {
    a,
    b,
    random
};

console.log(plugin.random, plugin.a, plugin.b);

var index = plugin.random;

export default index;
Copy the code

The current code does not reduce the code

  • vim index.js
import * as data from './plugin'

console.log(data.default.random)

export default data.default.random

Copy the code
  • Look again at the packaging resultsdist/payfun.rollbear.dev.es.js
const a = 1;
const b = 2;

function random() {
    console.log('random');
}

var plugin = {
    a,
    b,
    random
};

console.log(plugin.random);

var index = plugin.random;

export default index;
Copy the code

Although A and B are not used, they will still be packed in

Import * as data from ‘./plugin’ export default{}

So how do you trigger tree-shaking?

  • Output using export
  • For input use import (XXX) from ‘XXX’
  • For example

vim plugin.js

export const a = 1
export const b = 2

export function random() {
    console.log('random')}Copy the code

Vim index.js import a,b but not used

import {random,a,b} from './plugin'

console.log(random)

export default random
Copy the code
  • View packaging resultsdist/payfun.rollbear.dev.es.js
// dist/payfun.rollbear.dev.es.js
function random() {
    console.log('random');
}

console.log(random);

export default random;

Copy the code

We see that a and B are tree-shaking off.

Therefore, export default is not recommended in actual development