Fix 'Cannot find module ajv/dist/compile/codegen' Error
When you see this error:
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:
npm ls ajvExample output:
my-app@1.0.0
└─┬ json-schema-faker@0.5.0
└── ajv@8.12.0This 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:
npm install ajv@6.12.0or for Yarn:
yarn add ajv@6.12.0Then 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
"resolutions": {
"ajv": "6.12.0"
}Apply it:
npx npm-force-resolutions
npm installUseful when you can’t modify the parent dependency.
4. Update Your Dependencies
Some packages have already fixed their AJV imports.
Check for updates:
npm outdatedThen upgrade:
npm install your-library@latestOften 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:
import codegen from 'ajv/dist/compile/codegen';✔ Correct:
import Ajv from 'ajv';6. Example Fix for json-schema-faker
Older versions require AJV v6:
npm install json-schema-faker@0.5.0 ajv@6.12.0Or use resolutions for an entire monorepo.
7. Last Resort: Patch the Package
Only if nothing else works:
npm install patch-packageThen 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.