假设您需要在内部模块中使用打字稿/节点库,该模块分布在多个.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
无法访问。解决方案是什么?
观察:
如果我错了,请纠正我:
我已阅读: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{}
另外,在我看来,使用模块是优越的,因为你没有使用文件系统来引用你的类(这是推荐的方式?!) - 但只是把它们分开而不关心它们在哪里。
答案 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.List
,api.MyModel
等进行访问...
但是,既然你是为什么不去一路为你的API定义创建一个外部模块? :)
创建图书馆
不幸的是,目前我无法在此找到明确的资源。
TL;创建库的DR是:
index.ts
,重新导出您要在库中公开的所有定义--declaration
标志编译库文件以自动生成类型typings
添加package.json
条目,指向生成的index.d.ts
文件使用该库:
node_modules
文件夹中,与任何其他库一样import * as mylib from 'mylib'
:它会自动导入所有导出的定义和打字简要提及here
您还可以查看我写的there
的Library
和Usage
段落
如果我找到更好的资源,我会更新这个答案