webpack4之性能优化


打包性能优化

提升工具版本

npm, yarn, node,甚至是webpack的版本

在尽可能少的模块上应用loader
1
2
3
4
5
6
7
8
9
10
11
12
13
// webpack.config.js
module.exports = {
module: {
rules: [{
test: /\.js$/,
exclude: /node_module/, // 排除哪个文件夹
include: path.resolve(__dirname, '../src'), // 在指定的文件夹下执行loader
use: [{
loader: 'babel-loader'
}]
}]
}
}
合理的使用plugin

比如压缩代码,只需要在生产环境才压缩,开发环境就不用压缩了

处理第三方模块

第三方模块只打包一次。先新建一个第三方打包配置文件,进行一次打包。再打包

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
// package.json
{
"script": {
"build:third": "webapck --config ./build/webpack.third.js"
}
}

// ./build/webpack.third.js
const path = require('path')
const webpack = require('webpack')

module.exports = {
mode: 'production',
entry: {
vendors: ['react', 'react-demo', 'lodash'] // 将第三方模块作为入口文件
},
output: {
filename: '[name].third.js',
path: path.resolve(__dirname, '../third'),
library: '[name]'
},
plugins: [
new webpack.DllPlugin({ // 用这个插件来分析你这个库,将第三方映射关系放在.mainfest.json文件中。
name: '[name]',
path: path.resolve(__dirname, '../third/[name].mainfest.json')
})
]
}

// webpack.config.js
const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin')
const webpack = require('webpack')

module.exports = {
mode: 'production',
entry: './src/index.js',
plugins: [new HtmlWebpackPlugin({
template: './src/index.html'
}), new CleanWebpackPlugin(),
new AddAssetHtmlWebpackPlugin({ // 将第三方打包后的文件引入到html的文件中
filepath: path.resolve(__dirname, '../third/vendors.third.js')
}),
new webpack.DllReferencePlugin({ // 当webpack进行打包的时候,根据.mainfest.json对源代码进行分析,假如有这种对应关系,就不用node_modules的库
mainfest: path.resolve(__dirname, '../third/vendors.mainfest.json')
})
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
}