【发布时间】:2017-09-25 06:12:23
【问题描述】:
我想达到什么目的
我正在尝试在 TypeScript 中创建一个模块,该模块将包含所需类的每个导出。事实上,真正困扰我的是在我的类中有import 语句都是相对的,这并不是进一步维护的最佳方式。我只想使用绝对路径。
一旦转译,具有绝对路径的类(在生成的 JavaScript 中)具有错误的路径(因为它们没有被转换为相对路径,当与 tsconfig.json > outDir 选项一起使用时更糟)。
使用示例
让我们以下面的项目层次结构为例
root
|- helpers
|- MyHelper.ts
|- AnotherHelper.ts
|- calculators
|- MyCalc.ts
|- parsers
|- XmlParser.ts
|- JsonParser.ts
|- index.ts // currently holding export statements
我想做什么
我想要一个这样的index.ts 文件:
// a top-level module, resolved like the `node` strategy of NodeJS module resolution
export module IndexModule {
export { MyHelper } from "./helpers/MyHelper";
export { AnotherHelper } from "./helpers/AnotherHelper";
// do the same for every class in my project
}
那么我可以执行以下操作:
import { JsonParser } from "IndexModule"; // no relative nor absolute path
export class MyHelper {
public constructor(input: any){
var result: any = new JsonParser().parse(input);
// work with result ...
}
}
我在很多地方(在 SO,the github repo of TypeScript,...)看到我并不是唯一一个为导入的相对/绝对路径而苦苦挣扎的人。
我的实际问题是:是否可以创建这样一个模块(或机制),以便我可以在顶部容器中定义每个导出,并像使用 NodeJS 模块一样导入这个容器(如 @987654330 @) ?
我尝试了什么
第一次尝试
这是我实际拥有的index.ts 文件:
// index.ts is in the root directory of the project, it accesses classes with relative paths (but here, management is quite easy)
export { Constants } from "./helpers/Constants";
export { ConstraintCalculatorHelper } from "./helpers/ConstraintCalculatorHelper";
export { MomentHelper } from "./helpers/MomentHelper";
export { Formatter, OutputFormatterHelper } from "./helpers/OutputFormatterHelper";
// ... doing this for each class I have in my project
第二次尝试
declare module IndexModule {
export { Constants } from "./helpers/Constants";
export { ConstraintCalculatorHelper } from "./helpers/ConstraintCalculatorHelper";
export { MomentHelper } from "./helpers/MomentHelper";
export { Formatter, OutputFormatterHelper } from "./helpers/OutputFormatterHelper";
// error : Export declarations are not permitted in a namespace
}
第三次,第四次,第N次尝试
尝试declare namespace、export module 等等……但没有运气。
也尝试declare module "IndexModule,导致错误:环境模块声明中的导入或导出声明无法通过相对模块名称引用模块
旁注
我不是 NodeJS / 模块 / 命名空间方面的专家,所以我可能对某些东西不太了解。如果是这样,如果有人能指出我误解了什么,我将不胜感激。
Relevant link here that shows the actual problem.
配置:
- NodeJS v7.2
- TypeScript v2.2
tsconfig.json:
{
"compileOnSave": true,
"compilerOptions": {
"removeComments": false,
"sourceMap": true,
"module": "commonjs",
"target": "es6",
"noImplicitAny": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"outDir": "./bin/LongiCalc"
}
}
【问题讨论】:
-
旁注:我想我们都可以欣赏你的帖子的努力和格式:)
-
@jhhoff02 啊,谢谢!实际上格式化帖子比写它要长;)
标签: node.js typescript module