按 4 的写法对 assets 直接更改会报警:
(node:51633) [DEP_WEBPACK_COMPILATION_ASSETS] DeprecationWarning: Compilation.assets will be frozen in future, all modifications are deprecated.
BREAKING CHANGE: No more changes should happen to Compilation.assets after sealing the Compilation.
Do changes to assets earlier, e. g. in Compilation.hooks.processAssets.
Make sure to select an appropriate stage from Compilation.PROCESS_ASSETS_STAGE_*.
原写法:
compiler.hooks.emit.tap('MyPlugin', compilation => {
for (const name in compilation.assets) {
if (name.endsWith('.js')) {
const source = compilation.assets[name].source();
const withoutComments = source.replace(/\/\*\*+\*\//g, '');
compilation.assets[name] = {
source: () => withoutComments,
size: withoutComments.length,
}
}
}
});
更新至:
const { Compilation, sources } = require('webpack');
class MyPlugin {
apply(compiler) {
compiler.hooks.thisCompilation.tap('MyPlugin', compilation => {
compilation.hooks.processAssets.tap({
name: 'MyPlugin',
stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,
}, assets => {
for (const asset in assets) {
if (asset.endsWith('.js')) {
compilation.updateAsset(asset, source => {
return new sources.RawSource(
source.source().replace(/\/\*\*+\*\//g, '')
);
});
}
}
});
});
}
}
注:
- assets 更新通过 processAssets 钩子,使用 compilation.updateAsset 来更新;
- processAssets 的 stage 状态清单:webpack.docschina.org/api/compila…
- sources 提供了一系列构造函数对 Source 类型进行处理[Source,RawSource,OriginalSource,ReplaceSource,SourceMapSource,ConcatSource,PrefixSource,CachedSource,SizeOnlySource,CompatSource],比较简单的可以使用 RawSource。还见到过包 webpack-sources,目前看和以上 Souce 的构造函数的功能是类似的;