How to write Webpack plugin which adds modules to the bundle on the fly based on other modules?

Solution 1:

This is a really complex question, but I can show how you can add additional dependencies to specific modules as if those were required from that module. This ensures that your added modules will be in the correct chunks and will also be removed if the parent module is removed from the bundle.

const CommonJsRequireDependency = require("webpack/lib/dependencies/CommonJsRequireDependency")

class MyPlugin {
  apply(compiler) {
    compiler.plugin("compilation", compilation => {
      compilation.plugin("succeed-module", module => {
        // this will be called for every successfully built module, but before it's parsed and
        // its dependencies are built. The built source is available as module._source.source()
        // and you can add additional dependencies like so:
        module.dependencies.push(new CommonJsRequireDependency("my-dependency", null))
      }
    }
  }
}

This is just one part of it. You'll also likely need to write your own loader to actually generate the translations (you can replace my-dependency above with my-loader!path/to/module to invoke it immediately) and some step after the chunks are created to perhaps extract them into a new asset and load them since they aren't actually required anywhere.