Node.js 在单独的文件nodejs+;打字稿

Node.js 在单独的文件nodejs+;打字稿,node.js,typescript,typescript-typings,typescript4.0,Node.js,Typescript,Typescript Typings,Typescript4.0,我不熟悉打字脚本,这可能是一个noob问题 我想扩展nodejs提供的全局变量 根据这一点,我写了这段代码,它正在工作 declare global { namespace NodeJS { interface Global { appRoot: string; } } } import path from "path"; global.appRoot = path.join(__dirname,'../');

我不熟悉打字脚本,这可能是一个noob问题

我想扩展nodejs提供的全局变量

根据这一点,我写了这段代码,它正在工作

declare global {
    namespace NodeJS {
      interface Global {
        appRoot: string;
      }
    }
  }
 
import path from "path";

global.appRoot = path.join(__dirname,'../');
console.log(global.appRoot)
但是我想把这个全局文件放到单独的文件中,如果我把它放到一个新的global.d.ts文件中

  • 我不知道出口什么
  • 我得到了这个错误
  • 全局范围的扩充只能直接嵌套在 外部模块或环境模块声明

    如果你这样做

      declare module NodeJS {
        export interface Global {
          appRoot: string;
        }
      }
    
    我得到这个错误 类型“Global&typeof globalThis”上不存在属性“approt”

    类型“Global&typeof globalThis”上不存在属性“approt”


    哪个版本的全局声明有效似乎总是取决于项目设置。在您的情况下,以下global.d.T应起作用:

    export {}; // make the file a module, to get rid of the warning
    
    declare global {
        namespace NodeJS {
            interface Global {
                appRoot: string;
            }
        }
    }
    

    也确保只有一个定义存在。

    如果我的答案不起作用,请考虑用TSCONFIG更新您的问题。