在 TypeScript 中如何将多个外部模块放入同一个命名空间? [英] How do you put multiple external modules into the same namespace in TypeScript?

查看:59
本文介绍了在 TypeScript 中如何将多个外部模块放入同一个命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我希望每个 .ts 文件有一个类.我有两个 .ts 文件,看起来像这样:

Say I want to have one class per .ts file. I have two .ts files, that look like so:

export module MyClasses { export class A {} }

export module MyClasses { export class B {} }

我不能这样做:

import MyClasses = module('A');
import MyClasses = module('B');

如何在单独的文件中定义类并将它们放入相同的命名空间"?此外,我们最终不得不执行以下操作:

How do I define classes in separate files and put them into the same "namespace"? Furthermore, we end up having to do something like:

MyClasses.MyClasses.A

代替

MyClasses.A

这种额外的层次结构有什么意义?这样您就可以在一个模块文件中拥有多个导出的模块?到目前为止,我想出的最佳解决方案是删除导出模块"(因为在编译 AMD 时导出类"似乎就足够了),这将类向上移动了一个层次级别.然后:

What's the point of this additional level of hierarchy? So that you can have more than one exported module in a module file? The best solution I've figure out so far is to remove "export module" (since "export class" seems to be sufficient when compiling AMD), which moves the class up one hierarchical level. Then:

import AModule = module('A');
module MyClasses{ var A = AModule.A; }
import BModule = module('B');
module MyClasses { var B = BModule.B; }

虽然它工作得很好,但并不完全简洁.没有更好的方法来做到这一点吗?

Though it works perfectly, it's not exactly succinct. Is there not a better way to do this?

推荐答案

不幸的是,似乎没有完美的解决方案,但我现在是这样解决的:

Unfortunately there does not seem to be a perfect solution but this is how I solved it for now:

文件控制器/MainController.ts":

File 'Controllers/MainController.ts':

class MainController {
    ...
}

export = MainController;

文件'Controllers/SecondController.ts':

File 'Controllers/SecondController.ts':

class SecondController {
    ...
}

export = SecondController;

文件控制器/命名空间.ts":

File 'Controllers/Namespace.ts':

import MainController = require('./MainController');
import SecondController = require('./SecondController');

export = { MainController, SecondController }

文件App.ts"(使用命名空间")

File 'App.ts' (where the 'namespace' is used)

import Controllers = require('Controllers/Namespace');

angular.module('app', [])
    .controller('MainController', Controllers.MainController)
    .controller('SecondController', Controllers.SecondController)

这为您提供了很好的智能感知,隐藏了 400 条导入语句,并使实际使用命名空间的代码非常干净......

This gives you nice intellisense, hides the 400 import statements away and keeps the code where the namespace is actually used pretty clean...

这篇关于在 TypeScript 中如何将多个外部模块放入同一个命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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