typescriptglobal-variablesdeno

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.

I want to declare the First variable that should be available globally everywhere without need to import it. (sort of like Deno variable is available)

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


Solution

  • The global object in Deno is: window / globalThis

    window.First = new FirstClass();
    

    For TypeScript compiler errors see: 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();