Tuesday, May 29, 2018

webpack plugin that adds other plugins

Leave a Comment

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

0 Answers

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment