Fixing the "'compilation' argument must be an instance of Compilation" Duplicate Webpack Version Error

This is probably going to be a very niche topic, but I occasionally run into this very obscure webpack error, and while I know how to fix it now, it caused much pain for a few weeks. It occurs when you're trying to build a yarn workspace with multiple packages using some version of webpack. If these webpack versions are mismatched, it can throw this error:

TypeError: The 'compilation' argument must be an instance of Compilation
    at Function.getCompilationHooks (<your-project-folder>/node_modules/@symfony/webpack-encore/node_modules/webpack/lib/NormalModule.js:227:10)
    at <your-project-folder>/node_modules/@symfony/webpack-encore/lib/webpack-manifest-plugin/index.js:56:24

The fix is simply to get all of your packages to use the same webpack version. To see what your project is using, run yarn why webpack at the workspace level. Correct these to use the same version and the error should go away. This can be a giant pain if webpack is being installed by a third party, like Storybook. Sometimes this means that I'm unable to update webpack to the latest version if my third party modules aren't there yet.

Webpack Encore

In my case, I have a Symfony monorepo, where a few packages are using webpack-encore and at least one is just using just webpack. My fix was to:

  1. make sure each package is using the same version of webpack-encore

  2. Then, run yarn why webpack to see which version of webpack encore is using.

  3. Finally, update the packages that AREN'T using encore to use that version of webpack.

The error should go away on the next yarn install/build. You may want to lock in to your webpack-encore version in your package.json to prevent if from auto-updating (see NPM semver docs).

Was this helpful? Did you find a better way? I'd love to hear it. Tweet me!