目录

上节: 代码分割(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)下(待更新)