且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在node.js打字稿中创建可写的全局变量

更新时间:2023-11-14 09:55:40

在TypeScript中,declare块用于描述您的全局变量.换句话说,它们是一种告诉TypeScript在全局命名空间中可以期望什么的方式,但是作为开发人员,您有责任确保它们确实在其中.

In TypeScript, declare blocks are used to describe your global variables. In other words, they are a way of telling TypeScript what it can expect in the global namespace — but it's your responsibility as a developer to make sure they are actually there.

创建(和描述)全局变量的方式取决于平台.

The way you can create (and describe) global variables depends on the platform.

浏览器(DOM)

import * as io from 'socket.io';

window.SocketServer = io.default();

declare global {
  interface Window {
    SocketServer: io.Server;
  }
}

需要@types/socket.io.通过访问window.SocketServer被消耗.

Requires @types/socket.io. Is consumed by accessing window.SocketServer.

Node.js

import * as io from 'socket.io';

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

global.SocketServer = io.default();

需要@types/socket.io@types/node.通过访问global.SocketServer被消耗.

Requires @types/socket.io and @types/node. Is consumed by accessing global.SocketServer.

通用

您还可以描述一个变量,该变量已经是您环境的一部分,并且客户端和服务器均可访问.

You can also describe a variable that is already a part of your environment and is accessible to both the client and the server.

这样的变量的一个例子是process-它是Node.js环境的一部分,但是Webpack之类的构建工具可以将其内容公开给客户端.

An example of such a variable would be process — it's a part of Node.js environment, but build tools like Webpack can expose its contents to the client.

import * as io from 'socket.io';

declare global {
  var SocketServer: io.Server;
}