当使用target/模块= esnext时,在打字稿中的__dirname等效



我需要计算一个相对于模块的文件系统位置的路径名。我正在使用Node.js 12.x.上的最新打字稿。由于tsconfig.json中的其他原因,我已经设置

        "target": "esnext",
        "module": "esnext",

这触发了一种严格对node.js支持ES6模块的模式。在该模式下,__dirname变量不可用,因为该全局未在Esanything规范中定义。我们应该做的是访问import.meta.url变量并提取目录名称。

有关示例,请参见此问题的最后一个答案:使用 - 实验模型flag

时__ dirname的替代方案

但是在Typescript eselecterpy Collection中,ImportMeta类未定义为包括url成员。因此,代码无法编译:

tdn.ts:7:25 - error TS2339: Property 'url' does not exist on type 'ImportMeta'.
7 console.log(import.meta.url);
                          ~~~

我无法在绝对键入的存储库中找到ImportMeta的定义。但这似乎是不当定义的。

更新:在node_modules//typescript/lib/lib.es5.d.ts中,我找到了以下内容:

/**
 * The type of `import.meta`.
 *
 * If you need to declare that a given property exists on `import.meta`,
 * this type may be augmented via interface merging.
 */
interface ImportMeta {
}

ugh ...

/update

在node.js 12.x文档页面上,它清楚地描述了 import.meta的形状,我们应该做以下操作:

import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

'__ dirname','__fileName'和'require'...等是nodejs特定的关键字,默认的TypeScript无法识别它们,尽管您需要知道编译器编译器编译TS文件到JS文件(默认情况下(,并且可以正常工作,以清除您可以在终端上运行此错误的错误(或Windows上的CMD(:

npm install --save @types/node

将安装nodejs类型的定义,并允许您在打字稿中编写nodejs程序时避免使用此类型的错误。

使用 import.metafileToURLupdate这有效...

根据node.org,ES模块中的两个commonjs变量特别是__dirname或__fileName。我们必须通过import.meta.url复制这些concomjs变量。来源:https://nodejs.org/api/esm.html#esm_no_filename_or_or_dirname

最新更新