【发布时间】:2020-12-31 00:43:35
【问题描述】:
我想在 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);
}
});
}
}()
],
这样就完成了工作,但有更好的方法吗?
【问题讨论】:
-
我不想让它看起来像是我实际上在提供问题的答案,我想展示 chenxsan 解决方案的样子,因为我对其进行了调整,而不是看起来像我在获得荣誉为它。
-
如果您认为您的改编会帮助其他人,那么您应该将其发布为替代答案。如果它不会给主题增加太多内容,那就保持现状。
标签: javascript webpack babel-loader