nino.porcino
nino.porcino

Reputation: 1183

how to promote a module to global in typescript?

I have a library contained in a module that I use very often, so I want to promote it as "global" and use without requiring it.

In pure JavaScript it's easy as

window.mylib = require("mylib")

but I'm finding it difficult to do in TypeScript because apparently you can't mix "module" and "ambient" code. So this doesn't work:

import MyLib = require("mylib"); 
window.mylib = MyLib;  
interface Window {
    mylib: mylib;
}

because the Window interface is augmented only for one file.

Is there a way to do that (that doesn't include generating a custom mylib.d.ts) ?

Upvotes: 2

Views: 693

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164139

You should do something like:

yourModule.ts

import MyLib = require("mylib"); 

export {};

declare global {
    interface Window {
        mylib: mylib;
    }
}

window.mylib = MyLib; 

And then you just import it when needed:

import "./yourModule";

It's shorty discussed in Global augmentation.

Upvotes: 4

Related Questions