webpack429x成神之路十六-代码分割code-spliting中

8次阅读

共计 1447 个字符,预计需要花费 4 分钟才能阅读完成。

目录

上节:代码分割 (code spliting) 上

上节目录如下:

分割异步代码

之前 src/index.js 里都是同步代码:

现在来写段异步逻辑,修改 src/index.js:

function getComponent() {const element = document.createElement('div');
  return import(/* webpackChunkName: "lodash" */ 'lodash').then(({default: _}) => {const element = document.createElement('div');
    element.innerHTML = _.join(['Hello', 'webpack'], ' ');
    return element;
  }).catch(error => 'An error occurred while loading the component');
}


// 按需加载,当点击了页面,才会引入 lodash,也是单页应用路由懒加载的实现原理
window.addEventListener('click', function(){getComponent().then(component => {document.body.appendChild(component);
  })
});

import()可以不加载文件并返回 promise, 参考:https://developer.mozilla.org…

现在来 npm run build:


因为 import()还只是个提案,我们得安装 @babel/plugin-syntax-dynamic-import 插件才能用:
npm i @babel/plugin-syntax-dynamic-import -D

babel.config.js 使用插件:

module.exports = {
  presets: [
    ["@babel/env", {
      // 设置打包后的代码将在哪些浏览器运行?只针它们做转化
      targets: {
        edge: "17",
        firefox: "60",
        chrome: "67",
        safari: "11.1",
      },
  
      // 目前 @babel/polyfill 依赖的 core-js@2,需要指定此选项并安装
      corejs: 2,
  
      /*
       * @babel/polyfill 会将所有高阶语法转化,配置 useBuiltIns 只转化项目中用到的语法
       *797k => 291k
       * 当 useBuiltIns: "usage" 时,入口文件就不需要 import "@babel/polyfill" 了
       * 当 useBuiltIns: "entry" 时,需要在入口文件里 import "@babel/polyfill"
       * */
      useBuiltIns: "usage"
    }
    ]
  ],
  plugins: ["@babel/plugin-syntax-dynamic-import"]
}

再次 npm run build,和之前一样会进行代码分割

修改 webpack/webpack.prod.js,注释 chunk 属性:

// 省略
 optimization: {
    // 配置代码分割
    splitChunks: {// 要分割哪些模块:all(推荐), async(默认,只分隔异步代码), and initial
      // chunks: 'all'  
    }
  }
// 省略

再次 npm run build,还是会代码分割,也就是 chunks 默认会对异步代码进行分割

当再把 src/index.js 改回同步代码,code spliting 就失效了

下节:代码分隔 (code spliting) 下(待更新)

正文完
 0