自定义 Webpack 插件:用于访问转换后代码的钩子

Custom Webpack plugin: Which hook for accessing transformed code

我正在尝试在 webpack 插件中的某个加载器完成其工作后获取加载器转换的文件内容。这通常是另一个加载程序的理想选择,但我还需要访问一个在翻译过程结束时调用的挂钩(因此选择编写插件)。我需要一个不同于 emit 的钩子吗?允许访问转换后的文件内容的参数的属性是什么?

    compiler.plugin('done', () => {
       // some finalization code
    });

    compiler.plugin('emit', (compilation, callback) => {
      compilation.chunks.forEach((chunk) => {
        chunk.forEachModule((module) => {
          let filename = module.resource;
          // I could load filename from the filesystem, but I need the content
          // of the file that's gone through the loader pipeline (ideally
          // after a certain loader, but I think at the end of the
          // pipeline would also be fine).
        })
     });

我正在使用 webpack 3,但我应该可以从 webpack 4 解决方案进行翻译。

我最终写了一个插件,它在 after-resolve 上动态注入一个加载器(你必须手动检查你想在哪个 "module" 中注入加载器以及它的位置)并且为 done 事件安装一个挂钩以将所有内容写入磁盘。