我不确定我是否错误地构建了我的打字文稿,所以这里可能会问错误的问题。
我有两个相关的类1接口在不同的文件在同一个文件夹。
我把它们包装在一个模块中,因为这感觉像是我应该在c#中做的。
这些都是angularjs,所以它有自己的DI,这可能很重要,但也可能不重要。
文件1:export module Module1{
export interface IService{
}
}
File2:
export module Module1{
export class Implementation implements IInterface{
...
}
}
文件3是angular代码,它使用了angular注入的IInterface实例。如果我使用require("./File2")
导入File2,它可以工作,但我宁愿导入整个Module1
,如下所示,所以我不必单独要求每个类(因为这显然是一个简化的情况)。
import authModule = require('Module1');
var assetStreamApp = angular.module("[])
.run(['IInterface'], (instance: IInterface) => {
instance.doSomething();
});
这可能吗?
我不想单独导入每个文件,然后为每个"模块"选择不同的别名来命名类型,当我觉得我应该能够这样做一次时。
编辑:在多读了一点之后,我想我已经弄明白了一些术语。我想在一个项目中使用typescript内部模块,但也使用AMD模块作为分割点,所以我可以使用webpack的代码分割。理想情况下,您应该只使用外部模块,而不是将内部模块与外部模块混合使用。
这已经在这里和这里详细讨论过了。
我建议……IService.ts:
interface IService {
}
export = IService;
Implementation.ts:
import IInterface = require("./IInterface");
class Implementation implements IInterface{
...
}
export = Implementation;
然后将它们适当地导入到文件中:
import IService = require("./IService");
import Implementation = require("./Implementation");
// use IService and Implementation here
将多个模块合并为一个模块
也就是说,如果你真的想,你可以使用上面的IService.ts
和Implementation.ts
,然后创建一个名为Module1.ts
的文件,在那里你导入和导出你的模块,像这样:
export import IService = require("./IService");
export import Implementation = require("./Implementation");
然后在你的代码中你可以这样使用它:
import Module1 = require("./Module1");
// use Module1.IService or Module1.Implementation here
将多个模块与ES6模块组合
顺便说一下,我想指出,如果你使用ES6模块,这样做是非常方便的…
IService.ts:
interface IService {
}
export default IService;
Implementation.ts:
import IInterface from "./IInterface";
export default class Implementation implements IInterface {
...
}
Module1.ts:
// re-export the modules
export {default as IService} from "./IService";
export {default as Implementation} from "./Implementation";
当你使用这个模块时,你可以很容易地访问你想要的东西。下面是一些import语句的示例:
// import only IService
import {IService} from "./Module1";
// import IService and Implementation
import {IService, Implementation} from "./Module1";
// or implement everything on a Module1 object
import * as Module1 from "./Module1";