我可以在保存文件输出之前使用 webpack hook 来修改文件输出吗?

ksh*_*ine 10 javascript webpack babel-loader

我想在 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);
            }
          });
        }
      }()
    ],
Run Code Online (Sandbox Code Playgroud)

这样就完成了工作,但是还有更好的方法吗?

che*_*san 10

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

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

Run Code Online (Sandbox Code Playgroud)