Fix 'Cannot find module ajv/dist/compile/codegen' Error

September, 9th 2024 2 min read

When you see this error:

plaintext
Cannot find module 'ajv/dist/compile/codegen'

it usually means you’re dealing with an AJV version mismatch. AJV v8 removed several internal modules, but some tools still try to import them. This often occurs with packages like older versions of webpack, eslint, json-schema-faker, and others that expect AJV v6 or v7.

Below is an updated and simplified guide to help you fix the issue quickly.


Why This Error Happens

The problem occurs because:

  • AJV v8 no longer includes ajv/dist/compile/codegen
  • Some packages still expect older AJV versions and try to import internal files directly
  • Your project may be mixing multiple AJV versions (common after big updates)

1. Check Which Package Is Using AJV

Run:

bash
npm ls ajv

Example output:

plaintext
my-app@1.0.0
└─┬ json-schema-faker@0.5.0
  └── ajv@8.12.0

This shows which library is incompatible.


2. Install a Compatible AJV Version (Most Reliable Fix)

If a dependency expects AJV v6 or v7, install that version:

bash
npm install ajv@6.12.0

or for Yarn:

bash
yarn add ajv@6.12.0

Then restart your dev server.


3. Force a Specific AJV Version (Resolutions)

If nested dependencies pull the wrong version, apply a forced resolution.

Add to package.json

json
"resolutions": {
  "ajv": "6.12.0"
}

Apply it:

bash
npx npm-force-resolutions
npm install

Useful when you can’t modify the parent dependency.


4. Update Your Dependencies

Some packages have already fixed their AJV imports.

Check for updates:

bash
npm outdated

Then upgrade:

bash
npm install your-library@latest

Often this resolves the error without force-downgrading AJV.


5. Verify Import Paths (Your Own Code)

Make sure you are NOT importing internal AJV files:

❌ Wrong:

js
import codegen from 'ajv/dist/compile/codegen';

✔ Correct:

js
import Ajv from 'ajv';

6. Example Fix for json-schema-faker

Older versions require AJV v6:

bash
npm install json-schema-faker@0.5.0 ajv@6.12.0

Or use resolutions for an entire monorepo.


7. Last Resort: Patch the Package

Only if nothing else works:

bash
npm install patch-package

Then modify the dependency and create a patch file.

This should be temporary until an upstream fix is released.


Conclusion

You can fix the "Cannot find module 'ajv/dist/compile/codegen'" error by:

  • Installing AJV v6 (most reliable)
  • Forcing resolutions for nested dependencies
  • Updating outdated libraries
  • Avoiding imports of AJV internal modules

This issue is almost always caused by version mismatches—fix the version, and the error disappears.