typescript 打字稿:__dirname 值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36316118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript: __dirname value?
提问by Ng2-Fun
My folder structure is like this:
我的文件夹结构是这样的:
- app
- tsFolder
- XX.ts
- tsFolder
- 应用程序
- 文件夹
- XX.ts
- 文件夹
Code in XX.ts file:
XX.ts 文件中的代码:
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
.
我试过了:通过注释掉代码var __dirname: string;
,它的值__dirname
是:...../app
insead 指向当前文件夹,如...../app/tsFolder
.
Can anyone explain it?
谁能解释一下?
回答by Daniel Rosenwasser
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.
到你tsconfig.json
的compilerOptions
领域。
回答by Amid
I assume you refer to nodejs global variable __dirname.
我假设您指的是 nodejs 全局变量__dirname。
If it points to the ..../app it means that your XX.ts is compiled to the ..../app folder. And when resulting js file is run - __dirname points to its (js file) location.
如果它指向 ..../app 则意味着您的 XX.ts 已编译到 ..../app 文件夹。当生成的 js 文件运行时 - __dirname 指向它的(js 文件)位置。
And of course you should not declare new var __dirname. Instead either use nodejs typingsor just declare it manually like this:
当然,您不应该声明新的 var __dirname。相反,无论是使用的NodeJS分型或只是手动声明它是这样的:
declare var __dirname;
回答by U_R_Naveen UR_Naveen
I have tried npm i @types/node with no change in tsconfig . You make sure that working directory path length must be less than windows maximum limit.
我已经尝试过 npm i @types/node 没有改变 tsconfig 。您确保工作目录路径长度必须小于 Windows 最大限制。