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

北慕城南 提交于 2019-12-02 20:01:18

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!