简体   繁体   English

如何在 Deno 中定义全局变量?

[英]How to define global variable in Deno?

I am new to Deno and TypeScript but have plenty of experience using NodeJs and Javascript, I have stumbled on an issue of sorts, that I could have easily sorted out in NodeJs by simply adding global into the mix, however, that shows to be rather difficult in Deno for some reason.我是 Deno 和 TypeScript 的新手,但在使用 NodeJs 和 Javascript 方面有丰富的经验,我偶然发现了一个问题,我可以通过简单地在 NodeJs 中添加global来轻松解决这个问题,然而,这表明相当由于某种原因在 Deno 中很难。

I want to declare the First variable that should be available globally everywhere without need to import it.我想声明第First变量,它应该在全球范围内随处可用,而无需导入它。 (sort of like Deno variable is available) (有点像Deno变量可用)

Here is an example of the code I'm trying to get running:这是我尝试运行的代码示例:

/// 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
  }
}

I would run this code like this: deno run index.ts我会像这样运行这段代码: deno run index.ts

The global object in Deno is: window / globalThis Deno中的全局object是: window / globalThis

window.First = new FirstClass();

For TypeScript compiler errors see: How do you explicitly set a new property on `window` in TypeScript?对于 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM