Nelson
Nelson

Reputation: 3262

TSC cannot find name of Global Object

In my typescript code I am trying to access the __dirname global object: https://nodejs.org/docs/latest/api/globals.html

I am seeing a compile error: TS2304:Cannot find name '__dirname'. I can run the code without any issue. How can I get tsc to compile without error?

Upvotes: 38

Views: 40720

Answers (3)

Shawon Majid
Shawon Majid

Reputation: 21

If the above mentioned process do not work, check the tsconfig.json file and add the following if already not there,

"include": [
   "src/**/*",
 ],

I had the similar problem, I had a .ts file in this location src/services/promptService/prompt.ts

And the prompt.ts file was not finding __dirname and fs modules. Then I checked my tsconfig.json which had,

"include": [
      "src//*",
],

This was only compiling the files inside src directory and one level down, it wasn't able to compile 2 levels down. So changing this after following the above mentioned way, I was able to solve the problem.

Upvotes: 1

Sarthak S Kumar
Sarthak S Kumar

Reputation: 41

Just run

npm install @types/node --save-dev

or

pnpm install -D @types/node

Upvotes: 2

Nelson
Nelson

Reputation: 3262

In tsconfig.json add "node" to compilerOptions.types.

Example:

{
 "compilerOptions": {
  ...
  "types": [
    "node"
  ]
  ...
  }
}

Then run npm install @types/node --save-dev

Upvotes: 96

Related Questions