首页 > 解决方案 > 我可以在保存之前使用 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);
            }
          });
        }
      }()
    ],

这可以完成工作,但是有更好的方法吗?

标签: javascriptwebpackbabel-loader

解决方案


据我所知,您基本上是在用另一个字符串替换一些字符串。

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()],
};


推荐阅读