【问题标题】:How to declare a Global Variable in typescript [duplicate]如何在打字稿中声明全局变量[重复]
【发布时间】:2021-02-17 10:27:33
【问题描述】:

我继承了一个 Typescript 项目(有 .ts),但我呢?似乎无法锻炼如何在 Typescript 文件中创建全局变量并访问它。

我是 Typescript 的新手,所以请多多包涵。

我没有使用 Angular - 看到此链接 Typescript - Declare optional global variable

高度赞赏的任何指针

【问题讨论】:

标签: typescript google-chrome-extension global-variables


【解决方案1】:

这取决于您使用的是哪个运行时 typescript(例如:nodejs 或浏览器)

NodeJS 运行时

你必须 exportimport 你的变量。

// a.ts
export const foo = "bar";
// b.ts
import { foo } from 'a.ts';

浏览器运行时

可以使用全局对象window

window.foo = "bar"

您也可以使用exportimport,但在这种情况下,您必须使用构建器(webpacker、rollup 等)构建代码

从 typescript 3.4 开始,您还可以在两个运行时使用 globalThishttps://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#type-checking-for-globalthis

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 1970-01-01
    • 2017-06-10
    • 2014-01-21
    • 1970-01-01
    • 2012-11-28
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多