18

I'm trying to create a plugin that acts as a plugin wrapper, loading configuration, files, etc. and adding more plugins to the current webpack compilation process.

In the apply function I create the plugins and then apply them against the original compiler, something like this:

apply(compiler) {
  const plugins = [
    new HtmlWebpackPlugin(options1),
    new HtmlWebpackPlugin(options2),
    ...
  ];

  plugins.forEach((plugin) => {
    plugin.apply(compiler);
  });
});

My plugin doesn't add any hook to the webpack compiler but let other plugins with add them. It works nice when the container project uses webpack 4... but I found an error when working with different webpack versions.

One of the injected plugins is the html-webpack-plugin, which is a dependency of my plugin:

package.json

"dependencies": {
  "copy-webpack-plugin": "^4.5.1",
  "html-webpack-plugin": "^3.2.0",
  "webpack-bundle-analyzer": "^2.11.3"
}

So as you can imagine, I inject instances of those 3 plugins.

The problem comes when the project using my plugin uses webpack 3, because at some point, inside html-webpack-plugin requires NodeTemplatePlugin which is under html-webpack-plugin/node_modules/webpack. So as far as I understand, html-webpack-plugin has its own webpack which is webpack 4. Since the original passed compiler comes from webpack 3, and the one expected in NodeTemplatePlugin is webpack 4 I get an error when the latest tries to access compiler.hooks.thisCompilation because it doesn't exist in the compiler from webpack 3.

Funny thing is, in my package json webpack is defined as a peerDependency (same as in html-webpack-plugin) so it shouldn't be installed under the node_modules of my plugin.

"peerDependencies": {
  "webpack": "^2.0.0 || ^3.0.0 || ^4.0.0"
},

Any idea of why is this happening, or an alternative on how to inject plugins from another plugin?

If you need more context/code, you can check it here:
https://github.com/danikaze/generate-examples-index-webpack-plugin/blob/dev/src/ExamplesGenerator.js#L61

danikaze
  • 1,550
  • 2
  • 16
  • 34
  • Try to get `html-webpack-plugin` to work with webpack 3 by itself. Presumably, only a specific version or versions of the package will be compatible with webpack 3. If so, you'll need to bundle multiple different versions of your app or bundle both and load the correct one. – caesay May 29 '18 at 10:14
  • @caesay that's a good idea. Two versions of the plugin, one for webpack 3 and other one for webpack 4... or only one version with both html-webpack-plugin versions and select the proper one based on webpack version I guess... but I'd need to bundle it... – danikaze Jun 03 '18 at 23:11

0 Answers0