Search code examples
typescriptamd

TypeScript define AMD module by parts


Is it any way to split definition of AMD modules to several files?

Example what I mean:

// file WebApp/Deferred.ts
export module WebApp {
    export class Deferred {
        //...
    }
}

// file WebApp/Promise.ts
export module WebApp {
    export class Promise {
        //...
    }
}

// file init.ts
import WebApp = require("WebApp/Deferred", "WebApp/Promise"); // This is incorrect TS synatax
var a = new WebApp.Deferred();

Solution

  • This isn't a supported pattern. I recommend you create an index.ts file inside WebApp and export the common stuff from there. Sample index.ts:

    import deferred = require('./Deferred');
    import promise = require('./Promise');
    export var Deferred = deferred.WebApp.Deferred;
    export var Promise = promise.WebApp.Promise;
    

    So in your init.ts:

     import WebApp = require("WebApp/index");
     var a = new WebApp.Deferred();
    

    This is a common pattern on node.js where people create an index.js file in a folder. In fact node.js provides a shorthand for the import statement and there is a related feature request for TypeScript : https://typescript.codeplex.com/workitem/2125

    PS: I recommend not using internal modules when you are already using external modules (amd/commonjs). see : http://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1