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?
To solve the error "Cannot find name module", 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.
To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.
The Node runtime does not ship with its own type definitions, so we need to import those types separately. Where can we find them? They are also in npm but need to be installed separately.
In tsconfig.json
add "node"
to compilerOptions.types
.
Example:
{ "compilerOptions": { ... "types": [ "node" ] ... } }
Then run npm install @types/node --save-dev
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With