Webpack分包配置记录

拆包的目的

  1. 将更新频率较低的代码和内容频繁变动的代码分离,把共用率较高的资源也拆出来,最大限度利用浏览器缓存。
  2. 减少 http 请求次数的同时避免单个文件太大以免拖垮响应速度,也就是拆包时尽量实现文件个数更少、单个文件体积更小。

第二点实现文件个数少和单个文件小实际是矛盾的,因此要结合实际情况来处理,比如就可以利用webpack-bundle-analyzer来分析打包后的数据并进行调试

VUECLI的默认配置

vuecli默认配置(位于node_modules/@vue/cli-service/lib/config/app.js:28)如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// code splitting
if (isProd && !process.env.CYPRESS_ENV) {
webpackConfig
.optimization.splitChunks({
cacheGroups: {
vendors: {
name: `chunk-vendors`,
test: /[\\/]node_modules[\\/]/,
priority: -10,
chunks: 'initial'
},
common: {
name: `chunk-common`,
minChunks: 2,
priority: -20,
chunks: 'initial',
reuseExistingChunk: true
}
}
})
}

默认配置打包

新添加配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
if (process.env.NODE_ENV === 'production') {
// 公共代码抽离
config.optimization.splitChunks({
chunks: 'all', // initial async all
maxInitialRequests: 3, // 最大初始化请求数
maxAsyncRequests: 5, // 按需加载时最大的并行请求量
minSize: 30000, // 形成一个新代码块最小的体积
automaticNameDelimiter: '~', // 打包分隔符
name: true,
cacheGroups: {
vendor: {
chunks: 'all',
test: /node_modules/,
name: 'vendor',
minChunks: 2,
priority: 10
},
echarts: {
name: 'echarts',
test: /[\\/]node_modules[\\/](echarts)[\\/]/,
chunks: 'all',
enforce: true,
priority: 30
},
elementUI: {
name: 'elementUI',
test: /[\\/]node_modules[\\/](element-ui)[\\/]/,
chunks: 'all',
enforce: true,
priority: 30
},
femessageElementUI: {
name: 'femessageElementUI',
test: /[\\/]node_modules[\\/](@femessage)[\\/]/,
chunks: 'all',
enforce: true,
priority: 30
},
momentJs: {
name: 'momentJs',
test: /[\\/]node_modules[\\/](moment)[\\/]/,
chunks: 'all',
enforce: true,
priority: 30
},
luckyExcel: {
name: 'luckyExcel',
test: /[\\/]node_modules[\\/](luckyexcel)[\\/]/,
chunks: 'all',
enforce: true,
priority: 30
},
xlsx: {
name: 'xlsx',
test: /[\\/]node_modules[\\/](xlsx)[\\/]/,
chunks: 'all',
enforce: true,
priority: 30
},
// 不建议提取xlsxStyle 会导致很多细碎的包到业务包里面
// xlsxStyle: {
// name: 'xlsxStyle',
// test: /[\\/]node_modules[\\/](xlsx-style)[\\/]/,
// chunks: 'all',
// enforce: true,
// priority: 30
// },
mathJs: {
name: 'mathJs',
test: /[\\/]node_modules[\\/](mathjs)[\\/]/,
chunks: 'all',
enforce: true,
priority: 30
},
vxeTable: {
name: 'vxeTable',
test: /[\\/]node_modules[\\/](vxe-table)[\\/]/,
chunks: 'all',
enforce: true,
priority: 30
},
iconSvg: {
name: 'iconSvg',
test: /[\\/]src[\\/](icons)[\\/]/,
chunks: 'all',
enforce: true,
priority: 30
}
}
})
}

配置后打包情况

修改后打包情况

其他优化

  • 配置多线程打包:使用 thread-loader
  • 开启giz:使用compression-webpack-plugin,或者后端在NG端执行
  • 使用缓存:DLLplugin
  • 关闭sourceMap,看情况,不需要在生产环境调试就不开
  • 开启treeShaking,vue3支持更好,引入需要使用ES6语法按需引入

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!