code splitting

通过将 JS 应用分割成块,只有在某个应用的路由实际需要的时候才会进行加载。

three shaking

通过对代码文件进行静态分析,只将实际使用到的代码引入到结果文件中(去除掉永远也不会用的代码),减小代码体积。它是一种对无用代码的消除(dead code elimination)。
tree shaking 详细解释
JS 代码的处理过程:parse -> compile -> execution

在书写代码的时候尽量使用 import { xx } from 'xx.js' ,同时需要将副作用考虑在内。

针对于 webpack:
在 package.json 文件中注明 sideEffects: false,或者将含有副总用的文件进行标明。在使用 babel 的时候,babel 会将 ESM 转换为更为通用的 Commonjs 或者 UMD,这会对 tree shaking 产生干扰,所以可以用特定的配置告知 babel 不要进行转换。

  1. {
  2. "name": "webpack-tree-shaking-example",
  3. "version": "1.0.0",
  4. "sideEffects": false
  5. }

或者

  1. {
  2. "name": "webpack-tree-shaking-example",
  3. "version": "1.0.0",
  4. "sideEffects": [
  5. "./src/utils/utils.js"
  6. ]
  7. }

针对于 babel:

  1. {
  2. "presets": [
  3. ["env", {
  4. "modules": false
  5. }]
  6. ]
  7. }