webpack 优化插件粗讲及使用

1、hard-source-webpack-plugin

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

const HardSourceWebpackPlugin = require('hard-source-webpack-plugin');

module.exports = {
  // ......
  plugins: [
    new HardSourceWebpackPlugin() // <- 直接加入这行代码就行
  ]
}

您可以选择设置 HardSource 将其缓存写入和读取的位置,以及确定何时创建新缓存的哈希值。

new HardSourceWebpackPlugin({
  // Either an absolute path or relative to webpack's options.context.
  cacheDirectory: 'node_modules/.cache/hard-source/[confighash]',
  // Either a string of object hash function given a webpack config.
  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: 50 * 1024 * 1024
  },
}),

2、cache-loader

cache-loader 是一个 Webpack 加速构建的插件,可以通过缓存中间结果来提高构建性能。它可以缓存 loader 的输出结果,避免重复耗时的编译过程。

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          'cache-loader',
          'babel-loader'
        ],
        exclude: /node_modules/
      }
    ]
  }
};

通过以上配置,cache-loader 将会缓存每个 loader 的中间结果,当下次构建时遇到相同的输入时,将直接使用缓存结果,避免重复执行耗时的编译过程,从而加速构建。

请注意,保存和读取这些缓存文件会有一些时间开销,所以请只对性能开销较大的 loader 使用此 loader。

cache-loader 和 hard-source-webpack-plugin 都是用于优化 Webpack 构建性能的插件,它们有一些共同点,但也存在一些区别。下面是它们之间的一些主要差异:

  1. 缓存方式

    • cache-loadercache-loader 主要是缓存 loader 的输出结果。它会缓存每个 loader 处理后的文件,以避免重复的编译过程。
    • hard-source-webpack-pluginhard-source-webpack-plugin 则是提供了一个中间缓存,可以跨次构建持久化缓存模块和中间结果,以减少重复工作。
  2. 缓存粒度

    • cache-loadercache-loader 的缓存粒度是 loader 级别的,即每个 loader 处理的结果都可以被缓存。
    • hard-source-webpack-pluginhard-source-webpack-plugin 的缓存粒度更大,可以缓存模块和中间结果,从而跨多个 loader 和构建过程。
  3. 缓存策略

    • cache-loadercache-loader 的缓存策略相对简单&
  • 13
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值