在单独的文件nodejs + typescript中声明全局变量

declare global variable in seperate file nodejs+typescript

我是打字稿的新手,这可能是一个菜鸟问题。

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

根据这个 blog 我写了这段代码并且它正在工作

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

global.appRoot = path.join(__dirname,'../');
console.log(global.appRoot)

但是我想把这个全局文件放到一个单独的文件中,如果我把它移到一个新的 global.d.ts 文件中

  1. 我不知道要导出什么
  2. 我遇到了这个错误

Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.

如果这样做

  declare module NodeJS {
    export interface Global {
      appRoot: string;
    }
  }

我收到这个错误 属性 'appRoot' 在类型 'Global & typeof globalThis' 上不存在。

Property 'appRoot' does not exist on type 'Global & typeof globalThis'.

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

export {}; // make the file a module, to get rid of the warning

declare global {
    namespace NodeJS {
        interface Global {
            appRoot: string;
        }
    }
}

还要确保只存在其中一个定义。