html-webpack-plugin icon indicating copy to clipboard operation
html-webpack-plugin copied to clipboard

Webpack 5: The 'compilation' argument must be an instance of Compilation

Open ebuchmann opened this issue 6 years ago • 34 comments

Expected behaviour

Should correctly update the html file with script tags.

Current behaviour

Trying to update my project to webpack 5 beta 16.

Getting an error running webpack-dev-server. When I remove the html-webpack-plugin from my config it compiles fine, but keep getting the following error:

  TypeError: The 'compilation' argument must be an instance of Compilation
  
  - JavascriptModulesPlugin.js:116 Function.getCompilationHooks
    [irisroot]/[html-webpack-plugin]/[webpack]/lib/javascript/JavascriptModulesPlugin.js:116:10
  
  - NodeTemplatePlugin.js:34 compiler.hooks.thisCompilation.tap.compilation
    [irisroot]/[html-webpack-plugin]/[webpack]/lib/node/NodeTemplatePlugin.js:34:42
  
  
  - Hook.js:14 Hook.CALL_DELEGATE [as _call]
    [iris]/[tapable]/lib/Hook.js:14:14
  
  - Compiler.js:864 Compiler.newCompilation
    [iris]/[webpack]/lib/Compiler.js:864:30
  
  - Compiler.js:905 hooks.beforeCompile.callAsync.err
    [iris]/[webpack]/lib/Compiler.js:905:29
  
  
  - Hook.js:18 Hook.CALL_ASYNC_DELEGATE [as _callAsync]
    [iris]/[tapable]/lib/Hook.js:18:14
  
  - Compiler.js:900 Compiler.compile
    [iris]/[webpack]/lib/Compiler.js:900:28
  
  - Compiler.js:445 Compiler.runAsChild
    [iris]/[webpack]/lib/Compiler.js:445:8
  
  - child-compiler.js:110 compilationPromise.Promise
    [irisroot]/[html-webpack-plugin]/lib/child-compiler.js:110:21
  
  - new Promise
  
  - child-compiler.js:109 HtmlWebpackChildCompiler.compileTemplates
    [irisroot]/[html-webpack-plugin]/lib/child-compiler.js:109:31
  
  - cached-child-compiler.js:344 PersistentChildCompilerSingletonPlugin.compileEntries
    [irisroot]/[html-webpack-plugin]/lib/cached-child-compiler.js:344:21
  
  - cached-child-compiler.js:211 isCacheValidPromise.then
    [irisroot]/[html-webpack-plugin]/lib/cached-child-compiler.js:211:47
  
  - next_tick.js:68 process._tickCallback
    internal/process/next_tick.js:68:7
  
  - loader.js:834 Function.Module.runMain
    internal/modules/cjs/loader.js:834:11
  
  - node.js:283 startup
    internal/bootstrap/node.js:283:19
  
  - node.js:622 bootstrapNodeJSCore
    internal/bootstrap/node.js:622:3
  
Html Webpack Plugin:

Environment

Node.js v10.16.3 darwin 18.7.0 npm 6.9.0 yarn 1.22.0 [email protected] extraneous [email protected]

Config

    new HtmlWebpackPlugin({
      template: '../index.html',
    }),

It seems to just have a problem with this project. I tried to get a minimal repo going, except it works fine there. Not sure what's going on within this project, but I've been trying to remove other things to see if it's something else without any luck.

ebuchmann avatar May 29 '20 21:05 ebuchmann

@ebuchmann I had a similar error and it was because of having "webpack" installed in 2 places (monorepo), in such case it trigger this error (just having 1 works). Therefore, at least in my case, it is related to the node resolution.

artola avatar Jun 02 '20 19:06 artola

@ebuchmann I had a similar error and it was because of having "webpack" installed in 2 places (monorepo), in such case it trigger this error (just having 1 works). Therefore, at least in my case, it is related to the node resolution.

thx a lot !

biggu0 avatar Jul 30 '20 12:07 biggu0

what's progress of this issue ? i faced the same issue of "webpack": "^5.0.0-beta.30",

tianyingchun avatar Sep 12 '20 02:09 tianyingchun

what's progress of this issue ? i faced the same issue of "webpack": "^5.0.0-beta.30",

upgrade webpack to 5.1.0

chunlai996 avatar Oct 14 '20 04:10 chunlai996

@chunlai996 i upgrade to [email protected] & html-webpack-plugin@next (alpha.5) it also throw this issue.

TypeError: The 'compilation' argument must be an instance of Compilation\n

tianyingchun avatar Oct 17 '20 11:10 tianyingchun

I don't have this kind of error using [email protected], [email protected] and [email protected]. Here is my config

new HtmlWebpackPlugin({
  alwaysWriteToDisk: true,
  template: './www/public/index.html',
  filename: 'index.html',
}),
new HtmlWebpackHarddiskPlugin({
  outputPath: path.resolve(`${__dirname}/www`),
}),

@tianyingchun Do you have another pluygin inside your configuration that might occur this error ?

Thebarda avatar Oct 17 '20 11:10 Thebarda

I have also troubles to reproduce this issue

jantimon avatar Oct 17 '20 21:10 jantimon

@jantimon @Thebarda i have just remove all plugins, just remain

new HtmlWebpackPlugin({
      template: 'a/b/index.html',
      filename: join(pkgDir.sync(__dirname) || '', 'templates/index-prod.html'),
    }),

it still throw this error, if remove webpack-html-plugin the build works fine. i don't know the reason, i prepare the simple repo to reproduce this issue later.

tianyingchun avatar Oct 18 '20 01:10 tianyingchun

BTW i don't use webpack-cli i use webpack build api

//  multi compiler or single compiler.
  webpack(multiConfiguration[0], (err, stats) => {
if (err) {
        // Handle errors here
        return reject(err);
      }
      if (err) {
        return reject(err);
      }
      const { errors, warnings } = stats?.toJson();
      if (errors.length) {
        return reject(errors);
      }
      if (warnings.length) {
        return reject(warnings);
      }
      resolve({});
}

tianyingchun avatar Oct 18 '20 01:10 tianyingchun

can you add a console log where the error occurs and output compilation?

jantimon avatar Oct 18 '20 04:10 jantimon

@jantimon i try to start new repo with simplify webpack configurations to reproduce issue, but surprised it work fine can build success without errors, does not report me a error, the repo is https://github.com/tianyingchun/webpack5

Maybe i need to some more time to investigate for this, be cause my real project is more complex than this demo repo.

tianyingchun avatar Oct 18 '20 09:10 tianyingchun

@jantimon i found how to reproduce this issue, if i put create Html-webpack-plugin instance into another npm module e.g. please consider below structures.

in repo webpack-utils expose method createHtmlWebpackPlugin()

 export const createHtmlWebpackPlugin = () =>{
   const htmlPlugins: [];
   htmlPlugins.push(new HtmlWebpackPlugin({});
   return htmlPlugin;
}

in repo myProjects import {createHtmlWebpackPlugin} from 'webpack-utils'; const webpack = { mode:'production', ...... plugins: createHtmlWebpackPlugin(), .... };

and then run the webpack build it will throw errors.

if i copy all codes createHtmlWebpackPlugin() from webpack-utils into myProjects directly, it works fine.

Why ? Or is there a wrong while in usage of plugin of webpack?

tianyingchun avatar Oct 18 '20 13:10 tianyingchun

Got same problem. But with another config. Fir project I'm using gulp with webpack-stream and keep config into one file (gulpfile). There are only Vue loaders, styles and nothing else. Problem git during updating to new Vue 3, Vuex and also upgraded webpack from 4 to 5.

Fixed by downgrading webpack to 4th.

radiogron avatar Oct 18 '20 16:10 radiogron

I believe this might happen if multiple different webpack versions are installed - if webpack uses instanceOf to verify the passed values it might fail because compilation was constructed with a foreign Compilation constructor

jantimon avatar Oct 18 '20 16:10 jantimon

@jantimon no the two modules have the same version of wbpack & html-webpack-plugin, even if i use peerDependency for utils module it also throw this error.

tianyingchun avatar Oct 19 '20 00:10 tianyingchun

Can you please try to find the reason of this problem using node --inspect-brk ./node_modules/.bin/webpack and debugger statements?

jantimon avatar Oct 19 '20 07:10 jantimon

:) i totally migrate my code into single repo now, keep html-webpack-plugin with webpack within the same npm module it works fine :) when I have time, i will try to debug it, MAYBE this issue is related for learna package with paths definitions of tsconfig.json.

tianyingchun avatar Oct 19 '20 08:10 tianyingchun

Ok I found the root cause of my issue @jantimon is right

I believe this might happen if multiple different webpack versions are installed - if webpack uses instanceOf to verify the passed values it might fail because compilation was constructed with a foreign Compilation constructor

the situation is that I have the structure like

root | + node_modules/webpack | + example/node_modules/webpack

and while execution happen in example/ directory, then it resolves them to both locations. I am not digging into it deeper but the fastest resolution is to link the root library in nested project webpack: "file:../node_modules/webpack

for lerna project running bootstrap with --hoist should deal with it as well as for yarn workspaces

spamshaker avatar Oct 19 '20 17:10 spamshaker

Can confirm the workspaces issue. I'm using yarn workspaces, No dependencies are hoisted ("nohoist": ["**"]), and have the following structure.

  • /
    • config/
      • node_modules/
        • webpack/
        • webpack-cli/
        • webpack-dev-server/
        • html-webpack-plugin/
      • webpack.config.js
      • package.json
        • dependency: html-webpack-plugin
    • packages/
      • webapp/
        • node_modules/
          • webpack/
          • webpack-cli/
          • webpack-dev-server/
          • html-webpack-plugin/
        • package.json
          • devDependency: config
  • package.json
    • { "private": true, "workspaces": { "nohoist": [ "**" ], "packages": [ "config", "packages/*" ] } }

The packages/webapp package depends on the config package in the same workspace. The config package depends on the html-webpack-plugin, and also contains a shared webpack.config.js file. Running webpack serve -c node_modules/config/webpack.config.js in packages/webapp/ resolves webpack-cli (and dependencies) to packages/webapp/node_modules/. But the shared config/webpack.config.js resolves html-webpack-plugin (and dependencies) to config/node_modules/. This results in two versions of "something" being resolved.

I have a work around that cause the shared webpack.config.js to resolve plugins in the consuming (webapp) project instead of the shared config project.

Originally, the shared webpack.config.js has this require at the top.

const HtmlWebpackPlugin = require('html-webpack-plugin');

Changing it to the following causes html-webpack-plugin to resolve to a single version in packages/webapp/node_modules/, which fixes the problem.

const HtmlWebpackPlugin = require(require.resolve('html-webpack-plugin', { paths: [process.cwd()] }));

Edit: This might be a slightly more portable solution given that relative to the main module is probably where you want modules to be resolved.

const _require = id => require(require.resolve(id, { paths: [require.main.path] }));
const HtmlWebpackPlugin = _require('html-webpack-plugin');

Shakeskeyboarde avatar Oct 20 '20 04:10 Shakeskeyboarde

solved? I have the same problem

tw19920521 avatar Oct 20 '20 07:10 tw19920521