My folder structure is like this:
app
└─ tsFolder
└─ XX.ts
Code in XX.ts
file:
var __dirname: string;
console.log("__dirname: " + __dirname); // the output is undefined.
I have tried it: by comment out the code var __dirname: string;
, the value of __dirname
is: ...../app
insead of pointing to the current folder like ...../app/tsFolder
.
Can anyone explain it?
__dirname: It is a local variable that returns the directory name of the current module. It returns the folder path of the current JavaScript file. It returns the name the of current working directory.
The __dirname or __filename global variables are not available in ECMAScript module files. To solve the "__dirname is not defined in ES module scope" error, import and use the dirname() method from the path module. The dirname method takes a path as a parameter and returns the directory name of the path. Copied!
__dirname is an environment variable that tells you the absolute path of the directory containing the currently executing file.
The path. dirname() method returns the directories of a file path.
Just run
npm install --save-dev @types/node
And if that doesn't work on its own, add
"types": ["node"]
to your tsconfig.json
's compilerOptions
field.
I assume you refer to NodeJS global variable __dirname.
If it points to the ..../app
it means that your XX.ts
is compiled to the ..../app
folder. And when the resulting js file is run:
__dirname
points to its (js
file) location.
And of course, you should not declare new var __dirname
.
Instead, either use NodeJS typings or just declare it manually like this:
declare var __dirname;
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