【webpack4系列】webpack构建速度和体积优化策略(五)

文章目录

    • 速度分析:使用 speed-measure-webpack-plugin
    • 体积分析:使用webpack-bundle-analyzer
    • 使用高版本的 webpack 和 Node.js
    • 多进程/多实例构建
      • 资源并行解析可选方案
      • 使用 HappyPack 解析资源
      • 使用 thread-loader 解析资源
    • 多进程并行压缩代码
      • 方法一:使用 parallel-uglify-plugin 插件
      • 方法二:uglifyjs-webpack-plugin 开启 parallel 参数
      • 方法三:terser-webpack-plugin 开启 parallel 参数
    • 进一步分包:预编译资源模块
      • 分包:设置 Externals
      • 进一步分包:预编译资源模块
    • 充分利用缓存提升二次构建速度
    • 缩小构建目标与减少文件搜索范围
      • 缩小构建目标
      • 减少文件搜索范围
    • 使用Tree Shaking擦除无用的JavaScript和CSS
    • 使用webpack进行图片压缩(压缩有问题)
    • 构建体积优化:动态 Polyfill

速度分析:使用 speed-measure-webpack-plugin

使用speed-measure-webpack-plugin插件。

官网地址:https://github.com/stephencookdev/speed-measure-webpack-plugin#readme

示例效果:
【webpack4系列】webpack构建速度和体积优化策略(五)_第1张图片

安装:

npm i speed-measure-webpack-plugin -D

使用:

const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();

module.exports = smp.wrap({
  // 其他省略
  plugins: [
    new MyPlugin(), new MyOtherPlugin()
  ]
});

速度分析插件作用:

  • 分析整个打包总耗时
  • 每个插件和loader的耗时情况

体积分析:使用webpack-bundle-analyzer

示例代码:

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin()
  ]
}

安装:

npm i webpack-bundle-analyzer -D

可以分析哪些问题?

  • 依赖的第三方模块文件大小
  • 业务里面的组件代码大小

使用高版本的 webpack 和 Node.js

高版本的webpack和node.js降低了构建时间。

使用webpack4的优化原因:

  • V8 带来的优化(for of 替代 forEach、Map 和 Set 替代 Object、includes 替代 indexOf)
  • 默认使用更快的 md4 hash 算法
  • webpacks AST 可以直接从 loader 传递给 AST,减少解析时间
  • 使用字符串方法替代正则表达式

多进程/多实例构建

资源并行解析可选方案

  • parallel-webpack
  • HappyPack
  • thread-loader

使用 HappyPack 解析资源

原理:每次 webapck 解析一个模块,HappyPack 会将它及它的依赖分配给 worker 线程中。

安装:

npm i happypack -D

使用示例:

const HappyPack = require('happypack');
 
exports.module = {
  rules: [
    {
      test: /.js$/,
      // 1) replace your original list of loaders with "happypack/loader":
      // loaders: [ 'babel-loader?presets[]=es2015' ],
      use: 'happypack/loader',
      include: [ /* ... */ ],
      exclude: [ /* ... */ ]
    }
  ]
};
 
exports.plugins = [
  // 2) create the plugin:
  new HappyPack({
    // 3) re-add the loaders you replaced above in #1:
    loaders: [ 'babel-loader?presets[]=es2015' ]
  })
];

使用 thread-loader 解析资源

由于webpack4.x目前只能安装[email protected]版本,3.0.0以后的版本需要webpack5.x。

原理:每次 webpack 解析一个模块,thread-loader 会将它及它的依赖分配给 worker 线程中

npm i [email protected] -D

配置:

module: {
    rules: [
      {
        test: /.js$/,
        use: [
          {
            loader: "thread-loader",
            options: {
              workers: 3
            }
          },
          "babel-loader"
        ]
      }
    ]
  }

多进程并行压缩代码

方法一:

你可能感兴趣的:(webpack,webpack,前端,node.js)