Cannot find name '__dirname' Error in TypeScript [Solved]

avatar
Borislav Hadzhiev

Last updated: Feb 28, 2024
2 min

banner

# Cannot find name '__dirname' Error in TypeScript

To solve the error "Cannot find name __dirname", install the node typings 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

# Install the typings for Node.js

Open your terminal in the root directory of your project (where your package.json file is) and run the following command to install the typings for Node.js.

shell
npm i -D @types/node

install typings for node

If the error persists, try restarting your IDE.

# Add the typings to the types array in your tsconfig.json file

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" ], }, }
The code for this article is available on GitHub

That should fix the 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'));

We include the typings for Node, so we have access to the __dirname variable.

If you get the error __dirname is not defined in ES module scope, click on the link and follow the instructions.

# Delete your node_modules and reinstall your dependencies

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.

If you are on Windows, run the following commands in CMD.

cmd
# ๐Ÿ‘‡๏ธ (Windows) delete node_modules and package-lock.json rd /s /q "node_modules" del package-lock.json del -f yarn.lock # ๐Ÿ‘‡๏ธ clean npm cache npm cache clean --force npm install

If you are on macOS or Linux, issue the following commands in bash or zsh.

shell
# ๐Ÿ‘‡๏ธ (macOS/Linux) delete node_modules and package-lock.json rm -rf node_modules rm -f package-lock.json rm -f yarn.lock # ๐Ÿ‘‡๏ธ clean npm cache npm cache clean --force npm install

Make sure to restart your IDE and dev server if the error persists.

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

shell
npm i -D @types/node
The code for this article is available on GitHub

If the error persists, check out my __dirname is not defined in ES module scope article.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev