在打字稿内部模块中使用外部打字稿库

时间:2016-02-23 16:01:26

标签: javascript typescript

假设您需要在内部模块中使用打字稿/节点库,该模块分布在多个.ts文件中。

  

ApiRepositoryHelper.ts

import * as requestPromise from "request-promise"; 
module ApiHelper {
   class ApiRepositoryHelper extends DataRepositoryHelper {}
}
  

DataRepositoryHelper.ts

module ApiHelper {
   class DataRepositoryHelper {}
}

一旦添加该行: import * as requestPromise from "request-promise";DataRepositoryHelper无法访问。解决方案是什么?

观察:

如果我错了,请纠正我:

  1. Typescript内部模块可以分割为多个文件。
  2. 打字稿外部模块不能。
  3. 如果在内部模块范围之外添加对外部模块(比如jQuery)的引用(称为' A'),则在同一文件中,您可以在A中使用JQuery。但是内部模块' A'在项目的其余部分变得无法访问。
  4. 如果您有外部模块,则可以参考其他外部模块。
  5. 您无法在内部模块范围内引用外部模块,您将获得"命名空间中的导入声明无法引用模块。"
  6. 我已阅读:Correct way to reference modules from other modules in Typescript

    我也读过:

    Internal Module does not work if it has an import statement before it,但我不同意:

      

    如果没有内部模块,您可以很好地组织代码

    仅仅因为,

    module ApiHelper {
     class myClass {}
    }
    

    比整洁,

    import {Model} from "../../../lib/interfaces/model/Model";
    import {List} from "../../../lib/classes/helper/List";
    import {Serializable} from "../../interfaces/model/Serializable";
    import {DataRepository} from "../../../lib/interfaces/data/DataRepository";
    import {ModelFactory} from "../../interfaces/model/modelFactory";
    import {DefaultApiParser} from "./DefaultApiParser";
    import {ApiItemParser} from "./ApiParser";
    //Insert two hundred other imports here...
    
    export class MyClass{}
    

    另外,在我看来,使用模块是优越的,因为你没有使用文件系统来引用你的类(这是推荐的方式?!) - 但只是把它们分开而不关心它们在哪里。

1 个答案:

答案 0 :(得分:1)

相信我们! (那些试过并烧伤自己的人),modules/namespaces最好尽可能避免。

使用它们可能会让你解决许多无趣的问题,比如

另外" neater"值得商榷

  • 如果这可以让你感觉Java开发人员在使用Typescript之前已经存在了很多 - 在他们的文件顶部有许多导入,我希望他们的预期寿命不会低于Javascript开发人员的预期寿命。他们也是)。更严重的是,像Webstorm(12 EAP)这样的IDE会自动处理导入,甚至可以在编辑器中折叠它们,这样它们就不会污染"污染"您的代码视图。

  • 此外,您正在做的事情是某种import *而不是导入您需要的内容,从代码设计的角度来看是值得商榷的。

总体而言,使用外部模块可以更好地隔离。

现在假设您的代码分为两部分:API和实现,并且您希望在实现类中一次导入所有API定义,以避免多个import语句。

可以在API"部分"创建一个api.ts文件,重新导出所有内容,即

export * from 'interfaces/model/Model' 
export * from 'interfaces/model/Interfaces'
export * from 'interfaces/model/Serializables'
...

然后在实现类中,只需在命名空间下导入单个api.ts文件,例如

import * as api from '../api/api.ts'

然后可以将所有API定义的导出作为api.Listapi.MyModel等进行访问...

但是,既然你是为什么不去一路为你的API定义创建一个外部模块? :)

创建图书馆

不幸的是,目前我无法在此找到明确的资源。

TL;创建库的DR是:

  • 创建一个index.ts,重新导出您要在库中公开的所有定义
  • 使用--declaration标志编译库文件以自动生成类型
  • typings添加package.json条目,指向生成的index.d.ts文件

使用该库:

  • 将其放在node_modules文件夹中,与任何其他库一样
  • 只需import * as mylib from 'mylib':它会自动导入所有导出的定义打字

简要提及here

您还可以查看我写的there

LibraryUsage段落

如果我找到更好的资源,我会更新这个答案