Last updated: Feb 28, 2024
Reading timeยท2 min
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.
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.
npm i -D @types/node
If the error persists, try restarting your IDE.
types
array in your tsconfig.json
fileIf that doesn't help, make sure the types
array in your
tsconfig.json file contains "node"
.
{ "compilerOptions": { "types": [ // ... your other types "node" ], }, }
That should fix the error in your project.
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.
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.
# ๐๏ธ (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
.
# ๐๏ธ (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.
npm i -D @types/node
If the error persists, check out my __dirname is not defined in ES module scope article.