简体   繁体   English

NodeJS执行程序无法识别Typescript的CommonJS内部模块

[英]Typescript's CommonJS Internal Modules not recognized by NodeJS executor

I am creating a NodeJS application where I need to create internal modules to better organize my code logic and avoid having to write the full path when referencing such modules. 我正在创建一个NodeJS应用程序,我需要在其中创建内部模块以更好地组织我的代码逻辑,并避免在引用此类模块时不得不编写完整路径。

internal-module.ts 内部模块

export class A {
    test() {
  }
}

I have a bunch of files with exported classes in them, which are then all exported from one index file. 我有一堆文件,其中包含导出的类,然后全部从一个索引文件中导出。

index.ts 索引

export * from './internal-module'
export * from './internal-module2'

I am then generating a single definition file for all of these internal modules by using dts-generator . 然后,我将使用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';
}

Then I'm consuming such module as follows: 然后,我将使用以下模块:

consumer.ts 消费者

import {A} from "src/internal-module";

This all works from a Typescript's perspective - as in, I get intellisense after I generate the definition files... but then when running the actual NodeJS code (after also compiling the .ts files), the modules are not being found: 从Typescript的角度来看,所有这些都有效-例如,在生成定义文件后得到了智能感知...但是随后在运行实际的NodeJS代码(还编译了.ts文件之后)时,找不到模块:

Error: Cannot find module 'src/internal-module'

I noticed that in the compiled .js file there's this code: 我注意到在编译的.js文件中有以下代码:

consumer.js Consumer.js

var a = require("src/internal-module");

Seems like this is the same syntax that NodeJS uses for external modules, which searches through node_modules folder for. 看起来这是相同的语法NodeJS使用外部模块,它通过搜索node_modules文件夹。 Am I missing something? 我想念什么吗? Is the issue related to the way I'm compiling TS? 问题与我的TS编译方式有关吗?

I'm compiling TS with the suggested CommonJS mode: 我正在使用建议的CommonJS模式编译TS:

tsconfig.json tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "declaration": true
    }
}

尝试使用相对路径(以./为前缀):

import {A} from "./src/internal-module";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM