目錄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就失效了