webpack - code splitting

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文件里面。

相关文章
相关标签/搜索