HMR实现原理
加快构建速度
速度分析
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();
//将默认的webpack配置文件包裹起来
const webpackConfig = smp.wrap({
plugins: [
new MyPlugin(),
new MyOtherPlugin()
]
});
优化方法
- 使用高版本的webpack和Node.js
- 开启多进程并行解析资源:thread-loader
module.exports = {
module: {
rules: [
{
test: /\.js$/,
include: path.resolve("src"),
use: [
"thread-loader",
// your expensive loader (e.g babel-loader)
]
}
]
}
}
- 开启多进程并行压缩:terser-webpack-plugin 开启 parallel 参数
const TerserPlugin = require('terser-webpack-plugin');
module.exports = {
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,
}),
],
},
};
- 进一步分包
- 第三方包使用CDN: 设置Externals
new HtmlWebpackExternalsPlugin({
externals: [
{
module: 'react',
entry: 'https://cdn.bootcss.com/react/15.6.1/react.js',
global: 'React'
},
{
module: 'react-dom',
entry: 'https://cdn.bootcss.com/react/15.6.1/react-dom.js',
global: 'ReactDOM'
},
],
})
- 预编译资源模块(基础包):DllReferencePlugin
- 分离公共js:SplitChunks
- 充分利用缓存提升二次构建速度
- babel-loader
module: {
rules: [
{
test: /\.js$/,
//?cacheDirectory=true 开启缓存
use: 'babel-loader?cacheDirectory=true'//使用babel-loader解析ES6
}
]
}
- terser-webpack-plugin
optimization: {
minimizer: [
new TerserPlugin({
parallel: true,//开启多进程并行压缩代码
cache: true,//开启缓存
}),
],
},
- 使用 cache-loader 或者 hard-source-webpack-plugin
const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
module.exports = {
output: {
filename: 'bundle.js'
},
plugins: [
new HardSourceWebpackPlugin()
]
};
- 缩小构建目标
- module.rules中配置include、exclude
- resolve(extension、alias)
- 使用TreeShaking删除无用的js和css
使用:
webpack 默认支持,在 .babelrc 里设置 modules: false 即可
production mode的情况下默认开启
优化打包体积
1、SplitChunksPlugin插件,抽取公共代码
module.exports = {
mode: 'development',
...
optimization: {
splitChunks: {
chunks: 'all',
},
},
};