Fixing the "Cannot Find Module 'typescript'" Error When Using tsup
If you're using tsup to bundle your TypeScript project and encounter an error like this:
Error: Cannot find module 'typescript'
Don't worry—this is a common issue, and the fix is straightforward. This article will walk you through the cause of the issue, how to fix it, and additional considerations to prevent similar problems in the future.
Why Does This Error Happen?
The error occurs because tsup internally relies on TypeScript but doesn't always install it as a dependency. When you run tsup
and it tries to process .ts
files, it needs TypeScript to be available. If it isn't installed, the build process fails with the "Cannot find module 'typescript'" error.
How to Fix the Error
1. Install TypeScript
The quickest and most reliable way to fix this issue is to install TypeScript as a development dependency:
npm install --save-dev typescript
After the installation, verify that TypeScript is available by running:
npx tsc --version
This command should return the installed TypeScript version.
2. Re-run Your Build Command
Once TypeScript is installed, try running your build command again:
npm run build
This should now complete successfully without the missing module error.
Additional Considerations
Check Your package.json
To prevent this issue from happening again, ensure that your package.json
includes TypeScript in the devDependencies
section:
"devDependencies": {
"typescript": "^5.3.0"
}
If TypeScript is missing, manually add it and run:
npm install
Clear and Reinstall Dependencies
If the issue persists, it could be due to a corrupt or incomplete node_modules
folder. Try deleting node_modules
and package-lock.json
, then reinstalling everything:
rm -rf node_modules package-lock.json
npm install
Then run the build command again.
Ensure tsup is Up to Date
Using an outdated version of tsup may also cause compatibility issues. Upgrade it by running:
npm update tsup
If you're still encountering issues, try installing the latest version explicitly:
npm install --save-dev tsup@latest
Use a TypeScript Configuration File (tsconfig.json
)
While tsup can work without a tsconfig.json
file, having one in your project ensures TypeScript is configured correctly. Run:
npx tsc --init
This will generate a basic tsconfig.json
file, which you can customize as needed.
Finally
The "Cannot find module 'typescript'" error is frustrating but easy to fix by ensuring TypeScript is properly installed. By following the steps outlined here—installing TypeScript, verifying dependencies, and keeping your tools up to date—you can avoid similar issues in the future.
If you're still experiencing problems, check the tsup documentation and GitHub issues page, as updates and bug fixes are regularly released.
Comments ()