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

前端 未结 1 1439
醉话见心
醉话见心 2021-02-02 05:55

I have a problem with writing a Webpack plugin for a translation service.

The goal is to:

  1. Get names (and source code) of all required modules during compil
相关标签:
1条回答
  • 2021-02-02 06:30

    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.

    0 讨论(0)
提交回复
热议问题