Fix Gatsby 'cannot find module gatsby-cli/lib/reporter'

By

Learn how to fix the Gatsby Cannot find module gatsby-cli/lib/reporter error by deleting node_modules and reinstalling with yarn instead of npm install.

~~~

This records a historical dependency incident. Switching from npm to Yarn is not a general fix for missing modules. Use the package manager and lockfile already chosen by the project.

The fix for the Gatsby Cannot find module 'gatsby-cli/lib/reporter' error is to delete node_modules and reinstall your dependencies from scratch. Let me show you what happened to me, and why this works.

I created a site using Gatsby and I ran gatsby develop to start a local server.

But a weird error showed up, coloring with red my terminal:

Gatsby error

What does the error mean?

Node.js throws Cannot find module when it can’t resolve a file that some code is trying to load. In this case the missing file is lib/reporter, part of the gatsby-cli package. It’s the module Gatsby uses to print progress and errors to the terminal.

That file lives inside node_modules. If Node can’t find it, node_modules is in a broken state. Maybe an install got interrupted halfway. Maybe a package was updated but only partially written to disk.

A very common cause is mixing package managers. If you run npm install at one point and yarn at another, each tool lays out node_modules in its own way, and you can end up with a folder that’s half one and half the other.

The fix

After a few searches across GitHub and StackOverflow (I found a lot of people with the same problem!) this is what fixed the error.

First, I deleted node_modules:

rm -rf node_modules

then I used yarn instead of npm install:

yarn

This installed all the packages again, from scratch, in a consistent state.

Finally I ran gatsby develop and it worked.

Terminal showing successful Gatsby development server startup with build process completing and localhost URLs displayed

Not sure what the cause problem is/was, but I tried again running npm install instead of yarn and it didn’t work. My project had a yarn.lock file, so my guess is yarn recreated the exact dependency tree the project was built with, while npm resolved a slightly different one.

What if this doesn’t fix it for you?

A few variations of the same cleanup helped other people hitting this error.

Delete the lockfile too, package-lock.json or yarn.lock, before reinstalling. You lose the pinned versions, so dependencies get resolved again, but that can clear a corrupted resolution.

Also check if you have an old global gatsby-cli installed. A version mismatch between a global CLI and the local Gatsby packages in your project can cause similar module errors. Prefer running the local version through your project’s npm scripts.

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about js: