1

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?

1 Answer 1

1

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 -->
Sign up to request clarification or add additional context in comments.

1 Comment

Luckily, those third party scripts won't need MyModule at loading time so we just need to add MyModule to the list of dependencies and save it to the global object as you suggested. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.