【问题标题】:Typescript - How to declare global variables on node.jsTypescript - 如何在 node.js 上声明全局变量
【发布时间】:2020-02-10 15:19:25
【问题描述】:

如何全局声明一些自定义变量?

使用示例

import './logger'; // custom module: Global logger is initialized. (using winston)

log.info('This is custom global logger.'); // access to log variable globally.

【问题讨论】:

标签: node.js typescript typescript-typings


【解决方案1】:

在 TypeScript 中,声明全局块用于描述向全局命名空间添加变量或声明全局变量。

Node.js

import * as io from 'socket.io';

declare global {
  namespace NodeJS {
    interface Global {
      SocketServer: io.Server
    }
  }
}

global.SocketServer = io.default();

注意:全局变量在某些情况下是可以的,即使有多个进程。当我们想要存储一个常量值时,推荐/常用它,例如失败期间的一些电子邮件 ID。 global.support_email = "somedl@domain.com"

引用可能重复:

How to use global variable in node.js?

How to create writable global variable in node.js typescript(使用打字稿)

How to use global variable in node.js?

【讨论】:

  • 谢谢。我解决了。就我而言,import * as winston from 'winston'; declare global { namespace NodeJS { interface Global { log: typeof winston.Logger; } } const log: winston.Logger; }
  • 很高兴听到
猜你喜欢
  • 2022-01-15
  • 2019-01-04
  • 2016-07-09
  • 1970-01-01
  • 2014-10-30
  • 2017-07-25
  • 2017-06-02
  • 2019-07-27
  • 2013-08-12
相关资源
最近更新 更多