javascript - TypeScript:如何从子模块导入类?

标签 javascript typescript ecmascript-6

我有一个同时使用 .ts 的 TypeScript 应用程序和 .d.ts文件。使用三重斜杠表示法进行引用 /// <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;
}

这样做的缺点是我的全局 namespace 被 var 污染了我不使用,因为我会使用 Service通过App.Service , 不是 APP_SERVICE .

最佳答案

如果您关心为模块创建一个漂亮的、可重用的、可维护的声明文件,首选方法是使用 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。这会将您所有的类型绑定(bind)到一个类型声明文件中,声明正确的子模块并尊重模块、子模块甚至外部模块之间的所有必要依赖关系。

  5. 将此文件复制到原始项目中的 custom-typings 目录,或将此 repo 提交到 typings registry所以其他人也可以从中获利 🙂,并使用正常的 typings i my-module-name 将其引入。

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

关于javascript - TypeScript:如何从子模块导入类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39154473/

相关文章:

javascript - 尝试在 Chrome 中运行时来自 Sigma.js 的 XMLHTTPRequest 错误 [似乎是它运行方式的独特之处]

css - 绑定(bind)到 'style.grid' 会引发 'sanitizing unsafe style value' 警告

Javascript从存储在索引上的数组内的对象获取键

javascript - 返回 Promise 而不是异步

javascript - Angular JS 多个 ngRepeat

javascript - 在 Ember.js 中使用复选框切换和绑定(bind) bool 值

angular - 如何有条件地引导 Angular 应用程序?

javascript - 将箭头函数分配给变量后导出与直接导出有什么区别?

javascript - 通过修改 HTTP header 使用不带 CORS 的 XMLHttpRequest?

java - Angular 2 : download file from Rest webservice