Fix node modules import errors in VS Code
By Flavio Copes
How to fix the Cannot find module fs error in VS Code by installing the @types/node package as a dev dependency and reloading the editor window.
Got this error in VS Code?
Cannot find module 'fs' or its corresponding type declarations.ts(2307)
You need to include the definition file for node in your project.
Run this:
npm install --save-dev @types/node
and reload the VS Code window.
To reload, open the command palette (cmd-shift-P on Mac, ctrl-shift-P on Windows) and run “Developer: Reload Window”. Sometimes “TypeScript: Restart TS Server” is enough.
Why does this error happen?
Your code is fine. The fs module exists, and the program runs.
The problem is on the editor side. VS Code uses TypeScript to analyze your code, and TypeScript needs type declarations to know what a module exports. Node.js built-ins like fs, path, and http don’t ship with declarations, they only exist at runtime.
The @types/node package fills that gap. It describes every built-in Node module, so the editor knows that fs exists and what readFile() looks like.
That’s why the same error shows up with any built-in:
Cannot find module 'path' or its corresponding type declarations.ts(2307)
One install of @types/node fixes all of them at once. It also fixes related complaints, like process or __dirname being unknown.
This happens in plain JavaScript projects too, not just TypeScript ones. VS Code runs the same analysis on .js files to power autocomplete.
Still broken? Check your tsconfig
If you installed the package, reloaded, and the error is still there, look at your tsconfig.json for a types field:
{
"compilerOptions": {
"types": ["vitest"]
}
}
Here’s the pitfall: when types is present, TypeScript loads only the packages listed there. Everything else in node_modules/@types gets ignored, including the @types/node you just installed.
The fix is to add it to the list:
{
"compilerOptions": {
"types": ["vitest", "node"]
}
}
If you don’t have a types field at all, you don’t need one. Without it, TypeScript picks up all installed @types packages automatically.
One more tip
@types/node is versioned to match Node.js releases. If you’re on Node 20, you can pin the matching declarations:
npm install --save-dev @types/node@20
This keeps the editor from suggesting APIs that only exist in newer Node versions than the one you run.
Related posts about node: