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

Node.js + TypeScript中找不到'./types/identity'模块的排查与解决

问题:Node.js + TypeScript项目启动时找不到'./types/identity'模块

项目结构

backend/
├── kids-service/
│   ├── src/
│   │   ├── index.ts
│   │   ├── router.ts
│   │   └── types/
│   │       └── identity.d.ts
├── auth-service/

错误信息

使用nodemon启动服务器时出现:

Error: Cannot find module './types/identity'
Require stack:
- /home/lenovo/palmyra-backend/kids-service/src/index.ts
    at Function.Module._resolveFilename.sharedData.moduleResolveFilenameHook.installedValue ...

相关代码

src/index.ts中引发错误的代码:

import express from 'express';
import http from 'http';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import compression from 'compression';
import cors from 'cors';
import mongoose from 'mongoose';
import router from './router';
import './types/identity'; // 此行引发错误

const app = express();

app.use(cookieParser());
app.use(bodyParser.json());

const server = http.createServer(app);

server.listen(8081, () => {
    console.log('Kids service running on http://localhost:8081');
});

TypeScript配置(tsconfig.json)

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "typeRoots": [
      "./node_modules/@types",
      "./src/types"
    ],
    "types": [
      "node",
      "express"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/types/**/*.d.ts"
  ]
}

identity.d.ts文件内容

declare namespace Identity {
  interface User {
    id: string;
    name: string;
  }
}

原因与解决方案

错误原因

  1. 导入声明文件方式错误:.d.ts类型声明文件如果是全局命名空间(如你用的declare namespace Identity),不需要手动import。你在index.ts里的import './types/identity'会让Node.js尝试把它当作普通模块加载,但该文件没有导出任何内容,不符合模块规范,因此报错找不到模块。
  2. tsconfig配置已覆盖类型文件:typeRoots已经包含./src/types,且include也覆盖了src/types/**/*.d.ts,TypeScript会自动识别这些类型声明文件,手动导入反而多余。

解决步骤

  1. 删除错误导入语句:直接删掉index.ts中的import './types/identity';这一行,此时TypeScript会自动从identity.d.ts读取全局命名空间类型,你可以直接使用Identity.User。
  2. 可选优化(推荐模块化类型):如果不想用全局命名空间,改成模块式声明:
    • 修改identity.d.ts:
      export namespace Identity {
        interface User {
          id: string;
          name: string;
        }
      }
      
    • 在需要使用的文件中正常导入:
      import { Identity } from './types/identity';
      // 使用示例
      const user: Identity.User = { id: '1', name: 'test' };
      

按上述修改后,启动项目即可解决找不到模块的问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 02:05:15