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

Express+TypeORM+TypeScript开发模式报EntityMetadataNotFoundError

问题:开发模式下TypeORM找不到实体元数据,生产模式运行正常

场景概述

基于ExpressJS + TypeORM + TypeStack开发的项目,用开发模式直接运行app.ts时,首次请求会触发实体元数据找不到的错误,具体报错:

node_modules/src/data-source/DataSource.ts:427
        if (!metadata) throw new EntityMetadataNotFoundError(target)
                             ^
EntityMetadataNotFoundError: No metadata for "user" was found.

但直接运行编译后的/dist/app.js时,所有功能正常。

现有配置信息

tsconfig核心配置

  • target: es2020
  • module: nodeNext
  • moduleResolution: nodeNext

package.json脚本配置

"type": "module",
  "scripts": {
    "start": "tsc -p . && node dist/app.js",
    "start:prod": "node dist/app.js",
    "dev": "ts-node-esm app.ts --watch",
    "test": "mocha -r ts-node/register src/**/*.ts",
    "test-dev": "nodemon --watch . --ext ts --exec \"mocha -r ts-node/register src/**/*.ts\"",
    "build": "rimraf dist && tsc -p .",
}

TypeORM配置文件(typeorm.config.ts)

config();
const baseDir = 'dist/src';

export const appDataSource = new DataSource({
  type: 'postgres',
  host: process.env.POSTGRES_DB_HOST,
  port: Number(process.env.POSTGRES_DB_PORT),
  username: process.env.POSTGRES_DB_USER,
  password: process.env.POSTGRES_DB_PASSWORD,
  database: process.env.POSTGRES_DB_DATABASE,
  synchronize: false,
  logging: true,
  entities: [baseDir + '/**/entity/*.entity.js'],
  migrationsRun: true,
  migrations: [baseDir + '/migrations/*.js'],
});

已尝试无效方案

将entities和migrations的路径后缀改为.ts,问题未解决。


解决方案

核心原因

开发模式用ts-node-esm直接运行.ts源码时,TypeORM配置里的baseDir指向了编译后的dist/src,但此时实体源码还未编译成.js;同时ts-node运行环境需要读取.ts格式的实体文件,路径不匹配导致元数据加载失败。

具体修复步骤

  1. 根据运行环境动态切换文件路径与后缀
    修改typeorm.config.ts,通过环境变量区分开发/生产环境的文件路径:

    config();
    // 读取环境变量,判断当前运行模式
    const isDev = process.env.NODE_ENV === 'development';
    const baseDir = isDev ? 'src' : 'dist/src';
    const fileExt = isDev ? '.ts' : '.js';
    
    export const appDataSource = new DataSource({
      type: 'postgres',
      host: process.env.POSTGRES_DB_HOST,
      port: Number(process.env.POSTGRES_DB_PORT),
      username: process.env.POSTGRES_DB_USER,
      password: process.env.POSTGRES_DB_PASSWORD,
      database: process.env.POSTGRES_DB_DATABASE,
      synchronize: false,
      logging: true,
      entities: [`${baseDir}/**/entity/*.entity${fileExt}`],
      migrationsRun: true,
      migrations: [`${baseDir}/migrations/*${fileExt}`],
    });
    
  2. 更新dev脚本,注入环境变量
    修改package.json中的dev命令,显式指定开发环境:

    "dev": "NODE_ENV=development ts-node-esm app.ts --watch"
    
  3. 校验实体类装饰器正确性
    确保实体类正确使用@Entity()装饰器,且装饰器内的名称与报错中的"user"一致:

    import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
    
    @Entity('user')
    export class User {
      @PrimaryGeneratedColumn()
      id: number;
    
      @Column()
      username: string;
      // 其他字段定义...
    }
    
  4. 优化tsconfig兼容性配置
    确保tsconfig.json中开启以下配置,避免模块导入冲突:

    {
      "compilerOptions": {
        // 已有配置...
        "esModuleInterop": true,
        "skipLibCheck": true
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 14:55:19