Question

Assuming I've implemented this two interesting Typescript libraries as AMD modules.

MathBasics.ts

module MathBasics {
    export function add(a: number, b: number) {
        return a + b;
    }
    export function substract(a: number, b: number) {
        return a - b;
    }
}
export = MathBasics

MathAdvanced.ts

module MathAdvanced {
    export function mult(a: number, b: number) {
        return a * b;
    }
    export function div(a: number, b: number) {
        return a / b;
    }
}
export = MathAdvanced

How can I combine them in one MathAll.ts library so client code doesn't have to reference both of it.

MathAll.ts

import MathBasics = require("MathBasics");
import MathAdvanced = require("MathAdvanced"); 

module MathAll {
    export var MathBasics: MathBasics;  
    export var MathAdvanced : MathAdvanced;
    //Error: Type reference cannot refer to container 

    export module MathBasics;
    export module MathAdvanced;
    //Error: '{' expected

    export MathBasics;
    export MathAdvanced;
    //Error: Unexpected token; 'module, class, interface, enum, import or statement' expected.

}

export = MathAll;

I don't care right now whether there are 1 or 3 requests being made. My question is more about development convenience than performance.

Was it helpful?

Solution

You can just add the following two lines to your MathAll.ts file:

export import MathBasics = require("MathBasics");
export import MathAdvanced = require("MathAdvanced"); 

This will allow you to essentially import both using the MathAll psudeo-module...

import math = require('./MathAll');

math.MathAdvanced....

But it can play some havoc with your auto-completion and there were some hints that this may be disallowed in the future, which will then break your program - so beware of using this trick.

So now I have shown how you could do it, hopefully you'll accept my suggestion that you don't do it (because you know I'm not saying "don't do it" just because I don't know how you could do it).

Organise your modules in a way that makes each one sensible to import in its own right. Is it such a hardship to import MathBasics when I need it, and MathAdvanced when I need it?

If you are hiding implementation details, that is another matter - but you definitely aren't hiding implementation details when you export import - because you are showing off all the details by exporting them straight out.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top