3

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.

9
  • You should write all of your code in TypeScript using modules. Commented Jan 5, 2017 at 15:19
  • 2
    Did you try window['Http'] = Http; ? Commented Jan 5, 2017 at 15:23
  • @Martin Thank you it works, if you consider writing the answer I'll mark it as correct... just in case anyone else has similar problem. Commented Jan 5, 2017 at 15:27
  • @SLaks Thank you, I will definitely take a look on that. Commented Jan 5, 2017 at 15:37
  • Ok. I have added this as an answer. Commented Jan 5, 2017 at 15:49

2 Answers 2

1

To add a browser global simply attach the item to the window object.

window['Http'] = Http;
Sign up to request clarification or add additional context in comments.

Comments

1

Use the special global syntax:

declare global {
    interface Window {
        you: IAreCookingWithFire;
    }

    var you: IAreCookingWithFire;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.