parliament
parliament

Reputation: 22914

Typescript - How to resolve internal modules at run-time

My bootstrapper.ts that gets run from the main.ts entry point looks like this (minus the references heading):

import Dialogs = App.Widgets.Dialogs;
declare var $ : JQueryStatic;


export class Bootstrapper { 
    static SiteLoad() { 
       var dialog = new Dialogs.LoginDialog();
       ...
    }
}

However, when main.ts attempts to load this file the first line immediately throws a reference error. That's when I realized importing an internal module doesn't add any dependencies to the define wrapper of the generated .js file.

So then how do I resolve internal modules at run-time? Is it the case that AMD is only compatible with external modules and I have to load internal ones along with external libraries in the entry point in main.ts?

I prefer the aliases syntax of internal modules over external ones. The code I have above looks much cleaner than when using external module syntax:

import Dialogs = module("Modules/App.Widgets.Dialogs");
declare var $ : JQueryStatic;


export class Bootstrapper { 
    static SiteLoad() { 
       var dialog = Dialogs.App.Widgets.Dialogs.LoginDialog(); //Seriously?
       ...
    }
}

That's just ugly. What to do?

UPDATE:

Steve, the approach you suggest has a limitation. In my original approach using internal modules I can do the following:

import Dialogs = App.Widgets.Dialogs;

declare var $ : JQueryStatic;

export class Bootstrapper { 
    static SiteLoad() { 

        var loginDialog1 = new Dialogs.LoginDialog();  //Instantiation      -OK
        var loginDialog2: Dialogs.LoginDialog;         //Type-Declaration   -OK
    }
}

In the approach you suggest I lose the ability to use the alias for type declarations:

import DialogsModule =  module("Modules/App.Widgets.Dialogs");

var Dialogs : DialogsModule.App.Widgets.Dialogs;

declare var $ : JQueryStatic;

export class Bootstrapper { 
    static SiteLoad() { 

        var loginDialog1 = new Dialogs.LoginDialog();   //Instantiation  -OK        
        var loginDialog2: Dialogs.LoginDialog;  //Type-Declaration -ERROR: The name "Dialogs" does not exist in the current context  
        var loginDialog3: DialogsModule.App.Widgets.Dialogs.LoginDialog;  //Must use full name instead
    }
}

Upvotes: 1

Views: 1124

Answers (1)

Fenton
Fenton

Reputation: 250882

You can alias a long module path like this:

import DialogModule = module("Modules/App.Widgets.Dialogs");
var dialogs = DialogModule.App.Widgets.Dialogs;
declare var $ : JQueryStatic;

export class Bootstrapper { 
    static SiteLoad() { 
       var dialog = dialogs.LoginDialog();
       ...
    }
}

You can mix AMD with plain JavaScript by including the appropriate files yourself - but I recommend picking one pattern to use in your program to make things simpler to understand.

Upvotes: 2

Related Questions