Reputation: 5826
I've been working on a small "library" that I would use for Http requests. It's written in TypeScript and it has one primary class which is Http
. I'd like to be able to use this class in my ordinary JavaScript after including my compiled bundle, so I'm thinking about the way to make it globally available.
I'm using gulp-tsify
as a compiler and it does compile my TypeScript into the es5 bundle, which is great, but in a different scope as a self-invoking function. When I rewrite my bundle after it's compiled (code below) it works fine, but how to achieve that without rewriting the bundle script?
What I mean is... my compiled TypeScript looks like this:
(function e(t,n,r){ ... })(function(require, module, exports){
...
// Somewhere here I've got var Http_1 = require('/...');
}, n, r)
// console.log(Http_1) -> undefined
when I declare the global http like that (manually)...
var http;
(function e(t,n,r){
...
})(function(require, module, exports){
...
// Somewhere here I've got var Http_1 = require('/...')
http = Http_1;
// or I can do this without the Http_1
http = require('./classes/Http');
}, n, r)
// console.log(http) -> everything's fine
... the user is able to use the http object, but I want it to be automatically done by the compiler.
I was thinking about something like declare var http = Http;
inside TypeScript, but I'm unable to achieve that because the Initializers are not allowed in ambient contexts.
Any thoughts on how it could be done? Thank you.
Upvotes: 3
Views: 1725
Reputation: 10858
Use the special global syntax:
declare global {
interface Window {
you: IAreCookingWithFire;
}
var you: IAreCookingWithFire;
}
Upvotes: 1
Reputation: 16300
To add a browser global simply attach the item to the window object.
window['Http'] = Http;
Upvotes: 1