You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js TypeScript包中如何从子目录导入模块?

问题分析与解决方案

你的报错源于三个关键配置错误:

  • paths配置位置错误:paths必须嵌套在compilerOptions对象内,当前放在tsconfig根节点的配置不会被TypeScript识别。
  • 文件结构与路径配置不匹配:实际源码在项目根目录,但include指定了["src"],paths也指向./src/...,和真实文件位置完全不符。
  • 缺少baseUrl配置:使用paths时必须配合baseUrl,否则TypeScript无法正确解析路径映射。

方案一:调整文件结构到src目录(推荐)

将所有源码移入src目录,让结构与配置匹配:

./src/index.ts
./src/controller/index.ts
./src/controller/my-controller.ts

然后修正tsconfig.json,将paths移至compilerOptions内,并添加baseUrl:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "declaration": true,
    "outDir": "./lib",
    "strict": true,
    "baseUrl": "./",
    "paths": {
        "my-package": ["./src/index"],
        "my-package/controller": ["./src/controller/index"]
    }
  },
  "include": ["src"],
  "exclude": ["node_modules", "**/__tests__/*"]
}

方案二:不调整文件结构,修改配置适配根目录

如果不想移动文件,直接修改tsconfig.json适配根目录源码:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "declaration": true,
    "outDir": "./lib",
    "strict": true,
    "baseUrl": "./",
    "paths": {
        "my-package": ["./index"],
        "my-package/controller": ["./controller/index"]
    }
  },
  "include": ["./index.ts", "./controller/**/*"],
  "exclude": ["node_modules", "**/__tests__/*"]
}

修改完成后重新执行TypeScript编译,import {MyController} from 'my-package/controller';即可正常识别模块及类型声明。

内容的提问来源于stack exchange,提问作者MarcS82

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 10:11:34