Skip to content

Tree Shaking

lesson/.babelrc

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{
  "presets": [
    [
      "@babel/preset-env", {
        targets: {
          chrome: "67",
        },
        useBuiltIns: 'usage'
    }]
  ]
}

index.js

1
import "@babel/polyfill";

此时运行npx webpack,会报出警告

1
2
When setting `useBuiltIns: 'usage'`, polyfills are automatically imported when needed.
  Please remove the `import '@babel/polyfill'` call or use `useBuiltIns: 'entry'` instead.

Tree Shaking

只打包引入的内容

Tree Shaking 只支持 ES Module

lesson/src/index.js

1
2
3
import { add } from './math';

add(1, 2);

lesson/src/math.js

1
2
3
4
5
6
export const add = (a, b) => {
  console.log(a + b);
}
export const minus = (a, b) => {
  console.log(a - b);
}

lesson/package.json

1
2
3
{
  "sideEffects": false,
}

有css时可以把css配置到sideEffects

1
2
3
4
5
{
  "sideEffects": {
    "*.css"
  }
}

lesson/webpack.config.js

1
2
3
optimization: {
  usedExports: true
},

开发环境下,minus还会在,只有在production环境下才会完全删除