【发布时间】:2016-05-25 13:01:28
【问题描述】:
我正在创建一个 NodeJS 应用程序,我需要在其中创建内部模块以更好地组织我的代码逻辑并避免在引用此类模块时编写完整路径。
internal-module.ts
export class A {
test() {
}
}
我有一堆文件,其中包含导出的类,然后全部从一个索引文件中导出。
index.ts
export * from './internal-module'
export * from './internal-module2'
然后我使用dts-generator 为所有这些内部模块生成一个定义文件。
index.d.ts
declare module 'src/internal-module' {
export class A {
test(): void;
}
}
declare module 'src/index' {
export * from 'src/internal-module';
export * from 'src/internal-module2';
}
然后我正在消费这样的模块:
consumer.ts
import {A} from "src/internal-module";
从 Typescript 的角度来看,这一切都有效 - 例如,在生成定义文件后我得到了智能感知......但是当运行实际的 NodeJS 代码时(在编译 .ts 文件之后),模块不是发现:
Error: Cannot find module 'src/internal-module'
我注意到在编译后的.js 文件中有这样的代码:
consumer.js
var a = require("src/internal-module");
似乎这与NodeJS 用于外部模块的语法相同,它在node_modules 文件夹中搜索。我错过了什么吗?问题是否与我编译 TS 的方式有关?
我正在使用建议的CommonJS 模式编译 TS:
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"declaration": true
}
}
【问题讨论】:
标签: javascript node.js typescript commonjs