TypeScript模块 [英] TypeScript modules

查看:87
本文介绍了TypeScript模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能在两个或多个文件中将两个或多个类添加到TypeScript中的同一模块中.像这样:

I am wondering if it is possible somehow to have two or more classes in two or more files added to the same module in TypeScript. Something like this:

//src/gui/uielement.ts
module mylib {
    module gui {
        export interface UIElement {
            public draw() : void;
        }
    }
}

//src/gui/button.ts
///<reference path='uielement.ts'/>
module mylib {
    module gui {
        export class Button implements UIElement {
            constructor(public str : string) { }
            draw() : void { }
        }
    }
}

可能会有几十个GUI类,因此不可能将它们全部放在同一个文件中.我所有的类都将在"mylib"模块中. 但是我该怎么做?

There will probably be dozens of GUI classes, so having them all in the same file will not be possible. And all my classes will be in the 'mylib' module. But how do I do that?

如果将module mylib {...}转换为函数,则所有文件中所有mylib块的所有内容都应包含在同一函数中.

If the module mylib {...} is translated into a function then all content of all mylib blocks in all files should be contained within the same function.

这有可能吗?

当我编译时,我得到这个:

When I compile I get this:

$ tsc src/gui/button.ts 
src/gui/button.ts(4,39): The name 'UIElement' does not exist in the current scope

推荐答案

这就是它的工作原理!如果您查看生成的javascript代码,它将作为接受对象(即模块对象")的匿名函数添加:

This is exactly how it works! If you look at the generated javascript code, it add as an anonymous function that accepts an object, the "the module object":

var mylib;
(function (mylib) {
    var Button = (function () {
        function Button(x) {
            this.x = x;
        }
        return Button;
    })();
    mylib.Button = Button;    
})(mylib || (mylib = {}));

如果查看最后一行(})(mylib || (mylib = {}));),则仅在现有变量为false(或计算结果为false,例如null)的情况下,它才会实例化新对象(mylib = {}). 这样,所有命名相同的模块"将合并到同一对象.

If you look at the last line (})(mylib || (mylib = {}));) you see that it instantiates a new ojbect (mylib = {}) only if the existing variable is false (or something that evaluates to false, like null). That way, all "modules" that are named the same will be merged to the same object.

因此,内部模块彼此延伸.我必须指出,我还没有弄清楚嵌套模块会发生什么.

Therefore, internal modules extend each other. I have to note that I have not quite figured out what happens to nested modules.

更新:如果我不使用嵌套模块语法,而是将其更改为点语法,那么您的代码将对我有用.例如:

Update: Your code works for me if I do not use the nested module syntax, but change it to the dot syntax. e.g.:

module mylib.gui {
}

代替

module mylib {
    module gui {
    }
}

我将尝试调查为什么会发生这种情况,据我所阅读的规范,两种方法应该相等.

I'll try to investigate in why this is happening, as far as I have read the spec, both ways should be equal.

更新:如果嵌套的引用模块标记为已导出,则它起作用:

Update: if the nested referenced module is marked as exported, it works:

module mylib {
    export module gui {
    }
}

这篇关于TypeScript模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆