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.

通俗来说就是把代码分成很多很多块(chunk)。

那为什么要分块呢?

之前,为了减少http请求,我们就把所有代码打包成一个单独的JS文件。但是如果JS文件过大的话,下载速度就很慢,得不偿失。

因此webapck实现了把代码分块,需要某块代码的时候再去加载。

Code Splitting主要有三种方法:

1.  Entry Points : Manually split code using entry configuration(通过增加入口文件)

2. Prevent Duplication : Use SplitChunksPlugin to dedupe and split chunks

3.Dynamic Import: Split code via inline function calls within modules

方法一就是增加入口文件

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

 

posted @ 2018-08-23 11:49  快饿死的鱼  阅读(552)  评论(0编辑  收藏  举报