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

执行yarn typeorm migration:run报错:缺失dataSource参数求助

解决TypeORM执行migration:run提示缺失dataSource文件的问题

现有配置

package.json 脚本

{
  "scripts": {
    "build": "tsc",
    "dev:server": "ts-node-dev --inspect --transpile-only --ignore-watch node_modules src/server.ts",
    "typeorm": "ts-node-dev ./node_modules/typeorm/cli.js"
  }
}

ormconfig.json

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": "test",
  "password": "test",
  "database": "gostack_gobarber",
  "migrations": ["./src/database/migrations/*.ts"],
  "cli": {
    "migrationsDir": "./src/database/migrations"
  }
}

问题原因

TypeORM从0.3.x版本开始废弃了ormconfig.json这类传统配置文件方式,改用DataSource类统一管理数据库连接与配置,旧的CLI命令逻辑无法识别原有配置,因此抛出缺失dataSource文件的错误。

解决方案

方案1:适配TypeORM 0.3+版本(推荐)

1. 创建DataSource配置文件

在src/database目录下新建data-source.ts,内容如下:

import { DataSource } from "typeorm";

export const AppDataSource = new DataSource({
  type: "postgres",
  host: "localhost",
  port: 5432,
  username: "test",
  password: "test",
  database: "gostack_gobarber",
  migrations: ["./src/database/migrations/*.ts"],
  cli: {
    migrationsDir: "./src/database/migrations"
  }
});

2. 更新package.json中的TypeORM脚本

修改typeorm命令,指定数据源配置文件路径:

{
  "scripts": {
    "build": "tsc",
    "dev:server": "ts-node-dev --inspect --transpile-only --ignore-watch node_modules src/server.ts",
    "typeorm": "ts-node-dev ./node_modules/typeorm/cli.js --dataSource src/database/data-source.ts"
  }
}

3. 重新执行迁移命令

yarn typeorm migration:run

补充:后续创建新迁移的命令

保持原有命令格式即可,CLI会自动读取DataSource中的配置:

yarn typeorm migration:create src/database/migrations/CreateNewTableName

方案2:降级到TypeORM 0.2.x版本

若不想修改配置结构,可回退到兼容ormconfig.json的旧版本:

  1. 卸载当前TypeORM版本
yarn remove typeorm
  1. 安装0.2.x稳定版本(例如0.2.45)
yarn add typeorm@0.2.45
  1. 重新执行原有迁移命令即可正常运行

注意事项

  • 若选择升级到0.3+版本,项目中原有数据库初始化代码需替换为AppDataSource.initialize(),替代旧版的createConnection()方法。
  • 检查tsconfig.json的路径配置,确保TypeORM能正确识别迁移文件与数据源配置的路径。

内容的提问来源于stack exchange,提问作者Renato Ide Ogata

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 07:18:19