【问题标题】:TypeScript: How to import a class from a submodule?TypeScript:如何从子模块导入类?
【发布时间】:2016-08-25 20:46:52
【问题描述】:

我有一个使用 .ts.d.ts 文件的 TypeScript 应用程序。使用三斜杠符号/// <reference path=...> 进行引用。我的应用有以下定义文件:

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 污染了,因为我将使用ServiceApp.Service,而不是APP_SERVICE

【问题讨论】:

    标签: javascript typescript ecmascript-6


    【解决方案1】:

    如果您关心为模块创建一个漂亮、可重用、可维护的声明文件,首选方法是使用typings,因为它可以很好地处理类型依赖管理和子模块等方面。

    1. 为您正在编写的类型创建一个单独的存储库。
    2. 添加typings.json 文件,其中包含主要类型的名称和路径。例如:

      {
        "name": "my-main-module",
        "main": "index.d.ts"
      }
      
    3. 将主模块的类型声明添加到index.d.ts,将子模块的类型声明添加到submodule-name.d.ts

      submodule.d.ts

      export interface submoduleInterface {
        someProp: number
      }
      

      index.d.ts

      import * as submodule from './submodule'
      
      export interface mainInterface {
        someProp: number
      }
      
    4. 运行typings bundle index.d.ts -o bundle.d.ts。这会将您的所有类型捆绑到一个类型声明文件中,声明正确的子模块并尊重模块、子模块甚至外部模块之间的所有必要依赖关系。

    5. 要么将此文件复制到您原始项目中的 custom-typings 目录,要么将此 repo 提交到 typings registry,以便其他人也可以从中获利?,并使用普通的 typings i my-module-name 将其拉入.

    这是包含所有代码的gist,以及生成的bundle.d.ts。这是一个 repo,它使用两个子模块 (redux-persist/constants) 作为外部依赖项 (redux),并最终提交到类型注册表。

    【讨论】:

    • 这是一个很好的答案。我将对我的打字结构进行另一次尝试。虽然我不打算公开我的项目和类型,但很高兴知道我将如何去做。在未来的某个时候,我可能会创建一个公共 API,所以我会需要它。谢谢:)
    • 虽然这可行,但在创建打字稿项目时,我没有看到任何简单的方法来生成此结构。当 tsc 可以输出它们时,没有人想创建自己的 d.ts 文件。我们如何使 tsc 输出可以从消费者库中轻松导入的内容。
    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 2019-03-09
    • 2020-12-06
    相关资源
    最近更新 更多