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 构建性能的插件,它们有一些共同点,但也存在一些区别。下面是它们之间的一些主要差异:
-
缓存方式:
cache-loader
:cache-loader
主要是缓存 loader 的输出结果。它会缓存每个 loader 处理后的文件,以避免重复的编译过程。hard-source-webpack-plugin
:hard-source-webpack-plugin
则是提供了一个中间缓存,可以跨次构建持久化缓存模块和中间结果,以减少重复工作。
-
缓存粒度:
cache-loader
:cache-loader
的缓存粒度是 loader 级别的,即每个 loader 处理的结果都可以被缓存。hard-source-webpack-plugin
:hard-source-webpack-plugin
的缓存粒度更大,可以缓存模块和中间结果,从而跨多个 loader 和构建过程。
-
缓存策略:
cache-loader
:cache-loader
的缓存策略相对简单&