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

NestJS中TypeOrm迁移文件生成至根目录,需指定到目标文件夹

解决TypeORM迁移文件生成路径问题

方案1:在DataSource配置中指定生成目录

修改你的ormconfig.ts,在数据源配置对象里新增migrationsDir字段,明确迁移文件的生成路径:

import * as dotenv from 'dotenv';
import { DataSource } from 'typeorm';

dotenv.config();

const connection = new DataSource({
  type: 'postgres' as const,
  host: 'localhost',
  port: 5432,
  username: 'username',
  password: 'password',
  database: 'database',
  entities: ['src/server/entity/*.{ts,js}'],
  migrations: ['src/server/migration/*.{ts,js}'],
  // 新增该行,指定迁移文件生成目录
  migrationsDir: 'src/server/migration',
  extra: {
    ssl: false,
  },
});

export default connection;

方案2:直接在生成脚本中指定路径

如果不想修改配置文件,可调整package.json中的migration:gen脚本,把生成路径直接写在命令里:

{
  "scripts": {
    "typeorm": "typeorm-ts-node-esm --dataSource ./ormconfig.ts",
    "migration:gen": "npm run typeorm migration:generate src/server/migration/",
  },
  "dependencies": {
    "typeorm": "^0.3.6"
  }
}

执行命令时需在末尾补充迁移文件名称,比如npm run migration:gen AddUserTable,文件会自动生成到指定目录。

验证配置

修改完成后,执行示例命令测试:

npm run migration:gen AddNewColumn

此时迁移文件会自动创建在src/server/migration/目录下,不再生成到项目根目录。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:00:47