一.编译速度分析
npm i -D speed-measure-webpack-plugin
webpack.config.js配置:
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();
module.exports = smp.wrap({
// ...webpack config...
});
二.配置缓存
webpack.config.js配置:
module.exports = {
...,
cache: {
type: "filesystem", // 使用文件缓存
},
};
三.配置多进程
npm i -D thread-loader
webpack.config.js配置:
module.exports = {
...,
module : {
rules : [
test : /\.css$/i,
use : [MiniCssExtractPlugin.loader, "css-loader", "postcss-loader",{
loader: "thread-loader",
options: { workerParallelJobs: 2, },
}]
]
}
}
关于此loader具体配置可以去thread-loader看。注意,这是需要在非常耗时的loader情况下才使用。
四.减小代码体积
js压缩
const TerserPlugin = require("terser-webpack-plugin");
module.exports = {
optimization: {
minimizer: [
new TerserPlugin({
parallel: 4, //核心数量
terserOptions: {
parse: {
ecma: 8,
},
compress: {
ecma: 5,
warnings: false,
comparisons: false,
inline: 2,
},
mangle: {
safari10: true,
},
output: {
ecma: 5,
comments: false,
ascii_only: true,
},
},
}),
],
},
};
抽离重复代码
module.exports = {
...,
splitChunks: {
// include all types of chunks
chunks: "all",
// 重复打包问题
cacheGroups: {
vendors: {
// node_modules里的代码
test: /[\\/]node_modules[\\/]/,
chunks: "all",
// name: 'vendors', 一定不要定义固定的name
priority: 10, // 优先级
enforce: true,
},
},
},
};
最小化 entry chunk
module.exports = {
optimization: {
runtimeChunk: true,
},
};
}
五.加快加载速度
import异步加载
let about = () => import('@/views/About.vue')
浏览器缓存
module.exports = {
...,
optimization: {
moduleIds: "deterministic",
},
};
CDN
export.modules = {
...,
output: {
publicPath: ctx.isEnvProduction ? 'https://xxx.com' : '', // CDN 域名
},
}
}
六.开启Gzip压缩
npm install compression-webpack-plugin --save-dev
webpack.config.js配置:
// webpack启用Gzip压缩
const CompressionPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = ['js', 'css'];
const isPRD = process.env.NODE_ENV === 'production';
module.exports = {
...,
configureWebpack: {
plugins: isPRD ? [
new CompressionPlugin({
filename: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp('\.(' + productionGzipExtensions.join('|') + ')$'),
threshold: 10240,
minRatio: 0.8
})
] : []
},
}