webpack: hard-source-webpack-plugin-速度优化

1、背景

  在项目实现的过程中,想在代码更改的同时,查看效果的改变,而这个时候长时间的编译等待,造成了额外的时间浪费。

2、简介

HardSourceWebpackPlugin是webpack的插件,为模块提供中间缓存步骤。为了查看结果,需要使用此插件运行webpack两次:第一次构建将花费正常的时间。第二次构建将显着加快(大概提升90%的构建速度)。

3、实现

安装:yarn add --dev hard-source-webpack-plugin(或者使用npm)。
并在webpack的插件配置中添加此插件:
文件路径:build/webpack.dev.conf.js:

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin')
...
module.exports = merge(baseWebpackConfig, {
    
    
  module: {
    
    
    rules: utils.styleLoaders({
    
     sourceMap: config.dev.cssSourceMap })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: '#cheap-module-eval-source-map',
  plugins: [
  	...
    // 缓存 加速二次构建速度
    new HardSourceWebpackPlugin({
    
    
      // Either an absolute path or relative to webpack's options.context.
      //  cacheDirectory是在高速缓存写入 ,设置缓存在磁盘中存放的路径
      cacheDirectory: './../disk/.cache/hard-source/[confighash]',
      // Either a string of object hash function given a webpack config.
      recordsPath: './../disk/.cache/hard-source/[confighash]/records.json',
      //configHash在启动webpack实例时转换webpack配置,并用于cacheDirectory为不同的webpack配置构建不同的缓存
      configHash: function (webpackConfig) {
    
    
        // node-object-hash on npm can be used to build this.
        return require('node-object-hash')({
    
     sort: false }).hash(webpackConfig);
      },
      // Either false, a string, an object, or a project hashing function.
      environmentHash: {
    
    
        root: process.cwd(),
        directories: [],
        files: ['./../package-lock.json', './../yarn.lock'],
      },
      // An object.
      info: {
    
    
        // 'none' or 'test'.
        mode: 'none',
        // 'debug', 'log', 'info', 'warn', or 'error'.
        level: 'debug',
      },
      // Clean up large, old caches automatically.
      cachePrune: {
    
    
        // Caches younger than `maxAge` are not considered for deletion. They must
        // be at least this (default: 2 days) old in milliseconds.
        maxAge: 2 * 24 * 60 * 60 * 1000,
        // All caches together must be larger than `sizeThreshold` before any
        // caches will be deleted. Together they must be at least this
        // (default: 50 MB) big in bytes.
        sizeThreshold: 100 * 1024 * 1024
      },
    }),
  ]
})

4、效果:(时间由不同的项目结构决定,仅供参考)

第一次构建:
在这里插入图片描述
第二次构建:
在这里插入图片描述
结论:提升了大约90%的构建速度~~

猜你喜欢

转载自blog.csdn.net/khadijiah/article/details/106626710