webpackwebpack-pluginwebpack-loader

Custom Webpack plugin: Which hook for accessing transformed code


I'm trying to get the loader transformed content of files after a certain loader in a webpack plugin has done its job. This would usually be ideal for another loader, but I also need access to a hook that is called when the translation process is over (hence the choice for writing a plugin instead). Do I need a different hook than emit and what are the properties of the arguments that give access to the transformed file content?

    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).
        })
     });

I'm using webpack 3, but I should be able to translate from webpack 4 solutions.


Solution

  • I ended up writing a plugin which injects a loader dynamically on after-resolve (you have to check manually which "module" you'd like to inject the loader in and also its position) and also installs a hook for the done event to write everything to disk.