webpack系列 - 充分利用缓存提升二次构建速度

682 阅读1分钟

目的:提升二次构建速度

缓存思路:

  • babel-loader 开启缓存

  • terser-webpack-plugin 开启缓存

  • 使用 hard-source-webpack-plugin

1, babel-loader 开启缓存

开启babel缓存,在第二次打包时,打包构建速度更快

在webpack配置文件webpack.config.js中开启babel缓存

module.exports = {
...
module: {
   rules: [
            {
                test: /\.(j|t)sx?$/,
                use: [{
                    loader: "babel-loader",
                    options: {
                        cacheDirectory: true
                    }
                }],
                exclude: /node_modules/,
            },
            ...
      ] }
      ...
}

项目yarn build 构建速度从 63523 ms 提升到 53047 ms

before:

after:

2,terser-webpack-plugin 开启缓存

webpack.TerserWebpackPlugin并行处理多个子任务,效率会更加的提高,且是webpack4官方推荐,有专人维护,并且连配置的方式都可以直接在optimization中配置。

开启terser-webpack-plugin ,构建速度再次提升到 50411 ms

terser-webpack-plugin 官方推荐,适配度高,且速度快

3,使用hard-source-webpack-plugin

yarn add hard-source-webpack-plugin -D

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');
module.exports = {
  // ......
  plugins: [
    new HardSourceWebpackPlugin() // <- 直接加入这行代码就行  
  ]
}