Code splitting is one of the most compelling features of webpack. This feature allows you to split your code into various bundles which can then be loaded on demand or in parallel. It can be used to achieve smaller bundles and control resource load prioritization which, if used correctly, can have a major impact on load time.webpack
通俗來講就是把代碼分紅不少不少塊(chunk)。web
那爲何要分塊呢?npm
以前,爲了減小http請求,咱們就把全部代碼打包成一個單獨的JS文件。可是若是JS文件過大的話,下載速度就很慢,得不償失。app
所以webapck實現了把代碼分塊,須要某塊代碼的時候再去加載。插件
Code Splitting主要有三種方法:code
1. Entry Points : Manually split code using entry configuration(經過增長入口文件)server
2. Prevent Duplication : Use SplitChunksPlugin to dedupe and split chunksblog
3.Dynamic Import: Split code via inline function calls within moduleswebpack4
方法一就是增長入口文件it
Project
index.js
print.js
webpack.common.js
運行結果:
這種方法最簡單,可是有不少缺陷,看着很難受
1. index.js和print.js文件都引入了lodash,重複的lodash module會被加載兩次
2.它很不靈活,不能動態的分隔業務和核心應用
此刻咱們須要把公共的lodash module提取出來。那咱們就可使用SplitChunksPlugin這個插件了
2. 防止重複,提取公共依賴
webpack.config.js
webpack4已經棄用CommonChunkPlugin了,使用SplitChunkPlugin就能夠了
運行結果:
相比上一次。運行時間少了100多ms, app.bundle.js和print.bundle.js的size都小了不少,lodash已經從這兩個文件中移除了。
可是這種方法還不能作到按需加載
3. Dynamic Imports 動態導入
使用import(),在webpack中的import()
是個分離點——split-point,用來把被請求的模塊獨立成一個單獨的模塊。
import()把
模塊的名字做爲一個參數,而且返回一個Promise: import(name)->Promise.
run : npm run server
顯然看到lodash沒有打包在app.bundle.js文件裏面。