如何在 Deno 中定义全局变量?
How to define global variable in Deno?
我是 Deno 和 TypeScript 的新手,但有很多使用 NodeJs 和 Javascript 的经验,我偶然发现了一个问题,我可以通过简单地在 NodeJs 中添加 [=13] 来轻松解决这个问题=] 然而,出于某种原因,这在 Deno 中显得相当困难。
我想声明 First
变量,该变量无需导入即可全局使用。 (有点像 Deno
变量可用)
这是我尝试获取的代码示例 运行ning:
/// index.ts
import { FirstClass } from './FirstClass.ts';
global.First = new FirstClass();
await First.commit();
/// FirstClass.ts
import { SecondClass } from './SecondClass.ts';
export class FirstClass {
constructor() {}
async commit() {
const second = new SecondClass();
await second.comment();
}
}
/// SecondClass.ts
export class SecondClass {
constructor() {}
comment() {
console.log(First); // Should log the FirstClass
}
}
我会 运行 这样的代码:
deno run index.ts
Deno中的全局对象是:window
/ globalThis
window.First = new FirstClass();
对于 TypeScript 编译器错误,请参阅:How do you explicitly set a new property on `window` in TypeScript?
declare global {
var First: FirstClass
interface Window { First: any; }
}
window.First = new FirstClass();
await First.commit();
我是 Deno 和 TypeScript 的新手,但有很多使用 NodeJs 和 Javascript 的经验,我偶然发现了一个问题,我可以通过简单地在 NodeJs 中添加 [=13] 来轻松解决这个问题=] 然而,出于某种原因,这在 Deno 中显得相当困难。
我想声明 First
变量,该变量无需导入即可全局使用。 (有点像 Deno
变量可用)
这是我尝试获取的代码示例 运行ning:
/// index.ts
import { FirstClass } from './FirstClass.ts';
global.First = new FirstClass();
await First.commit();
/// FirstClass.ts
import { SecondClass } from './SecondClass.ts';
export class FirstClass {
constructor() {}
async commit() {
const second = new SecondClass();
await second.comment();
}
}
/// SecondClass.ts
export class SecondClass {
constructor() {}
comment() {
console.log(First); // Should log the FirstClass
}
}
我会 运行 这样的代码:
deno run index.ts
Deno中的全局对象是:window
/ globalThis
window.First = new FirstClass();
对于 TypeScript 编译器错误,请参阅:How do you explicitly set a new property on `window` in TypeScript?
declare global {
var First: FirstClass
interface Window { First: any; }
}
window.First = new FirstClass();
await First.commit();