Fix - Cannot find name '__dirname' Error in TypeScript

avatar

Borislav Hadzhiev

Tue Mar 15 20222 min read

Fix - Cannot find name '__dirname' Error in TypeScript #

To solve the error "Cannot find name __dirname", install the node types by running npm i -D @types/node. If the error is not resolved, try adding node to your types array in tsconfig.json and restarting your IDE.

cannot find name dirname error

The first thing you need to do is make sure you have typings for Node.js installed. Open your terminal in the root directory of your project and run the following command.

shell
npm i -D @types/node

If the error is still not resolved, try restarting your IDE.

If that doesn't help, make sure the types array in your tsconfig.json file contains "node".

tsconfig.json
{ "compilerOptions": { "types": [ // ... your other types "node" ], }, }

That should fix the "Cannot find name '__dirname'" error in your project.

index.ts
import * as path from 'path'; // 👇️ "/home/borislav/Desktop/typescript" console.log(__dirname); // 👇️ "/home/borislav/Desktop/typescript/src/another-file.ts" console.log(path.join(__dirname, './another-file.ts'));

When the types option is specified, only the listed packages will be included in the global scope.

The example above makes sure we include ./node_modules/@types/node, so we have typings for the __dirname global variable.

If types is not specified in your tsconfig.json file, all @types packages are included in your compilation - node_modules/@types/*.

If the error is not resolved, try to delete your node_modules and package-lock.json files, re-run npm install and restart your IDE.

shell
rm -rf node_modules package-lock.json npm install

Make sure to restart your IDE if the error still persists. VSCode glitches often and a reboot solves things sometimes.

The __dirname global variable comes with the Node.js typings, so installing the package via npm i -D @types/node should resolve the issue.

Use the search field on my Home Page to filter through my more than 1,000 articles.