DT DT
DT DT

Reputation: 378

TypeScript: create global var from a module

We are updating our web app using TypeScript and now we are running into this problem. This is our static class, MyModule.js:

MyModule = {};
MyModule.Constants = function(){};
MyModule.Constants.WIDTH = 100;
MyModule.Constants.HEIGHT = 100;
.......

Now we change it to this, MyModule.ts:

module MyModule {
    export class Constants {
        public static WIDTH:number = 100;
        public static HEIGHT:number = 100;
        ....
    }
} 
export = MyModule;

This works fine for us, using import/require statement, but there are a few classes (in javascript) from a third party that we can't change, and they can't get to MyModule.Constants static properties because MyModule is undefined to them.

So is there anyway to code so to make MyModule and MyModule.Constants are globar var?

Upvotes: 1

Views: 1955

Answers (1)

Jeffery Grajkowski
Jeffery Grajkowski

Reputation: 4061

Assuming you're using AMD modules in the browser: the level of difficulty here depends on whether MyModule has to be defined for the third party code when the script is processed, or just before you call some particular function.

If the third party script will load ok then your "main" requires statement is the only thing that needs to change. (By main I mean the single entry point as RequireJS recommends.) All you need to do is add MyModule to the list of dependencies and save it to the global object.

require(["MyModule", ...], function(MyModule, ...) {
    (<any>window).MyModule = MyModule;
    // the rest of your code
});

window is cast to any here so that the compiler doesn't complain that window.MyModule isn't already defined.

If your third party script won't even load without MyModule being defined things gets tougher. I think the simplest solution would be to remove the export = MyModule; line to make that script not a module and load it individually/synchronously. So your HTML file would have something like this:

    <script type="text/javascript" src="scripts/MyModule.js"></script>
    <script type="text/javascript" src="thirdpartylib.js"></script>
    <script type="text/javascript" data-main="scripts/main" src="requirejs.js"></script>
    <!-- etc -->

Upvotes: 1

Related Questions