Javascript TypeScript:如何从子模块导入类?
我有一个使用Javascript TypeScript:如何从子模块导入类?,javascript,typescript,ecmascript-6,Javascript,Typescript,Ecmascript 6,我有一个使用.ts和.d.ts文件的TypeScript应用程序。引用使用三斜杠表示法//。我的应用程序具有以下定义文件: declare module APP { class Bootstrap { constructor(); } } 然后我声明一个名为“app”的模块,以便将其导入其他文件: declare module "app" { export = APP; } 假设我的Bootstrap类存在,然后使用以下方法导入Bootstrap类
.ts
和.d.ts
文件的TypeScript应用程序。引用使用三斜杠表示法//
。我的应用程序具有以下定义文件:
declare module APP {
class Bootstrap {
constructor();
}
}
然后我声明一个名为“app”
的模块,以便将其导入其他文件:
declare module "app" {
export = APP;
}
假设我的Bootstrap
类存在,然后使用以下方法导入Bootstrap
类:
import { Bootstrap } from 'app';
这很有效。
现在我在APP
上创建了一个子模块,如下所示:
declare module APP.Service {
class Async {
constructor();
}
}
我为子模块做了另一个声明:
declare module "app/service" {
export = APP.Service;
}
现在,当我像这样导入类Async
时:
import { Async } from 'app/service';
我收到以下错误消息:
Module '"app/service"' resolves to a non-module entity and cannot be imported using this construct.``
如何从子模块导入类?
注
通过声明全局var
,我找到了一个解决方法:
declare var APP_SERVICE: APP.Service.IService; // IService exists
并将其导出到我的模块上:
declare module "app/service" {
export = APP_SERVICE;
}
这样做的缺点是,我的全局名称空间被我不使用的
var
污染了,因为我将通过App.Service
,而不是App\u Service
,使用Service
来使用Service
,如果您想为模块创建一个漂亮的、可重用的、可维护的声明文件,首选的方法是使用,因为它可以很好地处理类型依赖关系管理和子模块等方面
typings.json
文件,其中包含主打字的名称和路径。例如:
{
"name": "my-main-module",
"main": "index.d.ts"
}
index.d.ts
,将子模块的类型声明添加到submodule name.d.ts
子模块d.ts
export interface submoduleInterface {
someProp: number
}
import * as submodule from './submodule'
export interface mainInterface {
someProp: number
}
索引d.ts
export interface submoduleInterface {
someProp: number
}
import * as submodule from './submodule'
export interface mainInterface {
someProp: number
}
typings bundle index.d.ts-o bundle.d.ts
。这将把所有类型绑定到一个类型声明文件中,声明正确的子模块,并尊重模块、子模块甚至外部模块之间所有必要的依赖关系自定义打字
目录,或者将此回购提交给,以便其他人也能从中获益。这是一个很好的答案。我再试试我的打字结构。虽然我不打算公开我的项目和打字,但我很高兴知道我会怎么做。在将来的某个时候,我可能会创建一个公共API,所以我需要它。谢谢:)虽然这样做很有效,但在创建typescript项目时,我看不到任何简单的方法来生成这种结构。当tsc可以输出d.ts文件时,没有人想创建自己的d.ts文件。我们如何使tsc输出可以轻松从消费者库导入的内容。