Internal module as single function

时间:2015-09-14 16:09:02

标签: module typescript internal

Why TS generates two functions, but not one?

It looks like we have one module separated between two files in TS:

module Main {
    export function P() {
    }
}
module Main {
    export function P2() {
         P();
    }
}

And it compile to JS as two functions:

var Main;
(function (Main) {
    function P() {
    }
    Main.P = P;
})(Main || (Main = {}));
var Main;
(function (Main) {
    function P2() {
        Main.P();
    }
    Main.P2 = P2;
})(Main || (Main = {}));

But I need such JS output file, so all modules content would be concatenated to single function:

var Main;
(function (Main) {
    function P() {
    }
    function P2() {
        P();
    }
    Main.P2 = P2;
})(Main || (Main = {}));

So I do not need to write additional export function to use in other parts of module with same name.


I know that I can write:

module Main {
    function F1() {
    }
    export function F2() {
        F1();
    }
}

But it is not a good idea, because sometimes I have very big classes and functions.

1 个答案:

答案 0 :(得分:1)

  

为什么TS会生成两个函数,但不会生成一个

只是编译器没有完成 。基本上module关键字(now called namespace)是简单转换a common namespacing pattern。特别是基于Immediately-invoked Function Expressions (IIFE)s的命名空间。