目录webpack
上节: 代码分割(code spliting)上web
上节目录以下:chrome
以前src/index.js里都是同步代码:npm
如今来写段异步逻辑,修改src/index.js:segmentfault
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...promise
如今来npm run build:浏览器
由于import()还只是个提案,咱们得安装 @babel/plugin-syntax-dynamic-import插件才能用:
npm i @babel/plugin-syntax-dynamic-import -Dbabel
babel.config.js使用插件:app
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就失效了