webpack打包优化
首先需要 监控 打包体积和 打包时间
webpack-bundle-analyzer 可以看到打包体积
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
// new BundleAnalyzerPlugin({
// analyzerMode: 'static',
// reportFilename: '../bundle-report.html',
// generateStatsFile: true,
// statsFilename: '../bundle-stats.json',
// openAnalyzer: true,
// }),
vue-cli-service build --analyze
npx webpack-bundle-analyzer bundle-stats.json 查看监控文件
SpeedMeasurePlugin 监控打包速度
const smp = new SpeedMeasurePlugin()
插件需要将webpack配置包裹起来
vue-cli配置如下
configureWebpack: smp.wrap(webpackConfig),
如果是webpack配置 直接 module.exports =smp.wrap(webpackConfig)
基础优化
- 压缩文件
new CompressionPlugin({cache: false, // 不启用文件缓存test: /\.(js|css|html|jpe?g|png|gif|svg)?$/i, // 压缩文件格式filename: '[path][base].gz[query]', // 压缩后的文件名algorithm: 'gzip', // 使用gzip压缩minRatio: 0.8, // 压缩比例,小于 80% 的文件不会被压缩deleteOriginalAssets: false, // 压缩后删除原文件}), -
分包和cache-loader
如果是异步import或require 就是异步chunk 会单独打包output: 现在除了入口文件 基本都是要用contenthash- optimization.splitChunks
cacheGroups:maxSize: 2 * 1000 * 1000, // 单个 chunk 最大体积限制 (1m)
minChunks: 2, // 如果被引用次数达到 将会单独打包priority: 20,权重 -
// 核心框架单独打包vue: {name: 'chunk-vue',test: /[\\/]node_modules[\\/](vue|vue-router|vuex)[\\/]/,priority: 20,},elementUI: {name: 'chunk-elementUI', // split elementUI into a single packagetest: /[\\/]node_modules[\\/]_?element-ui(.*)/, // in order to adapt to cnpmpriority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app},
- optimization.splitChunks
thread-loader:多线程构建
.use('thread-loader')
.loader('thread-loader')
.tap((options) => {
// 设置 thread-loader 的选项
options = {
workers: 10,
// 增加性能监控参数
workerParallelJobs: 50,
poolTimeout: 2000,
// 开启日志转发
workerNodeArgs: ['--trace-warnings'],
}
return options
})
.end()
HardSourceWebpackPlugin: 跨编译缓存 第一次构建后保存缓存 大幅度加快第二次编译 cache-loader是打包过程中缓存
plugins: [
new HardSourceWebpackPlugin(),]
https://blog.csdn.net/jijunqing321/article/details/125411096
浙公网安备 33010602011771号