javascript - 我可以在保存之前使用 webpack 挂钩来修改文件输出吗?
问题描述
我想在 webpack 和 babel 处理文件后对其进行操作。在保存新文件之前触发了一个emit
挂钩,但我看不到操作文件内容的方法。所以我决定使用afterEmit
钩子读取刚刚编写的文件,修改它,然后将其写回:
plugins: [
new class OutputMonitor {
apply(compiler) {
compiler.hooks.afterEmit.tap('OutputMonitor', compilation => {
if (compilation.emittedAssets.has('index.js')) {
let contents = fs.readFileSync('./dist/web/index.js', 'utf-8');
// Strip out dynamic import() so it doesn't generate warnings.
contents = contents.replace(/import(?=\("tseuqer-yb")/, 'console.log');
// Strip out large and large-alt timezone definitions from this build.
contents = contents.replace(large, 'null');
contents = contents.replace(largeAlt, 'null');
fs.writeFileSync('./dist/web/index.js', contents);
}
});
}
}()
],
这可以完成工作,但是有更好的方法吗?
解决方案
据我所知,您基本上是在用另一个字符串替换一些字符串。
processAssets
如果您正在运行 webpack 5,我相信您可以使用hook。
这是一个可以适应您的情况的示例:
const { Compilation, sources } = require('webpack');
class Replace {
apply(compiler) {
compiler.hooks.thisCompilation.tap('Replace', (compilation) => {
compilation.hooks.processAssets.tap(
{
name: 'Replace',
stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE,
},
() => {
// get the file main.js
const file = compilation.getAsset('main.js');
// update main.js with new content
compilation.updateAsset(
'main.js',
new sources.RawSource(file.source.source().replace('a', 'b'))
);
}
);
});
}
}
module.exports = {
entry: './wp.js',
plugins: [new Replace()],
};
推荐阅读
- r - 黄土平滑 - geom_smooth vs() loess()
- c# - 如何防止在 C# 的 Foreach 循环中生成重复项
- arrays - 使用匹配和不匹配条件识别哈希中的项目
- ios - UISearchBar 一旦被点击就会跳出位置
- marklogic - 将 IRI 序列作为绑定变量中的值传递给 sem:sparql 函数 - marklogic
- spring-mvc - 非常简单的带有百里香叶的 Spring MVC 示例不起作用
- graph-theory - 强制边缘方向 GraphViz
- node.js - 在移动设备上使用 Google Cloud Speech 永远不会返回 isFinal
- javascript - TypeScript:基于对象创建界面
- python-3.x - 替换方法和 for 循环