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

TypeORM执行migrate:create时迁移文件未保存到指定目录如何解决

问题描述

在使用Nest.js集成TypeORM搭建项目时,编写的ormconfig.json配置文件内容如下:

{
    "type": "mysql",
    "host": "localhost",
    "port": 3306,
    "username": "root",
    "password": "root",
    "database": "ferrari",
    "synchronize": true,
    "logging": false,
    "entities": [
        "typeorm/entity/**/*.ts"
    ],
    "migrations": [
        "typeorm/migration/**/*.ts"
    ],
    "subscribers": [
        "typeorm/subscriber/**/*.ts"
    ],
    "cli": {
        "entitiesDir":"typeorm/entity",
        "migrationsDir": "typeorm/migration",
        "subscribersDir":"typeorm/subscriber"
    }
}

项目当前目录结构:

-src
-typeorm
   -migrations
ormconfig.json
package.json

执行npm run migrate:create -n test命令时,生成的迁移文件没有遵循配置文件中的目录规则,直接保存到了项目根目录。需要定位出错原因,给出配置方法让迁移文件正确生成到typeorm/migration文件夹下。

出错原因

核心问题按出现概率从高到低排序:

  • 配置路径和实际目录名不匹配:配置中写的迁移目录是typeorm/migration(单数形式),但实际创建的目录是typeorm/migrations(复数形式,末尾多了s),TypeORM找不到指定路径时,会默认回退到命令执行的工作目录(项目根目录)生成文件。
  • 配置文件格式错误:贴出的ormconfig.json内容开头缺失左大括号{,如果实际文件确实存在这个格式问题,会导致JSON解析失败,TypeORM完全读不到自定义配置,直接使用默认规则生成文件。
  • npm脚本参数传递错误/硬编码路径覆盖配置:如果package.json里的migrate:create脚本额外写了--dir参数指定了根目录,或者执行命令时没有加--分隔npm参数和脚本参数,会导致CLI没有正确读取配置文件中的路径规则。
解决步骤
  1. 统一路径命名
    二选一即可:
    • 把typeorm目录下的migrations文件夹重命名为migration,和配置保持一致;
    • 把配置里的migrationsDir字段值改为typeorm/migrations,同时把migrations数组里的匹配规则改为"typeorm/migrations/**/*.ts",和实际目录名一致。
  2. 修复配置文件格式
    确保ormconfig.json是合法JSON格式,开头补全左大括号{,可通过JSON校验工具确认没有语法错误。
  3. 修正npm脚本配置
    打开package.json,检查scripts字段下的migrate:create配置,不要硬编码输出路径,TypeORM 0.2.x版本的标准写法参考:
    "scripts": {
      "migrate:create": "ts-node ./node_modules/typeorm/cli.js migration:create"
    }
    
    执行创建命令时,要加--分隔npm参数和CLI参数,正确命令格式:
    npm run migrate:create -- -n test
    
  4. 高版本TypeORM适配方案
    如果使用0.3.x及以上版本的TypeORM,官方已经废弃ormconfig.json的配置方式,建议改用data-source.ts管理配置,迁移创建脚本需要显式指定数据源文件,示例配置:
    // src/data-source.ts
    import { DataSource } from "typeorm"
    
    export const AppDataSource = new DataSource({
        type: "mysql",
        host: "localhost",
        port: 3306,
        username: "root",
        password: "root",
        database: "ferrari",
        synchronize: true,
        logging: false,
        entities: ["typeorm/entity/**/*.ts"],
        migrations: ["typeorm/migration/**/*.ts"],
        subscribers: ["typeorm/subscriber/**/*.ts"],
    })
    
    对应脚本修改为:
    "scripts": {
      "migrate:create": "typeorm-ts-node-commonjs migration:create -d ./src/data-source.ts"
    }
    
    执行命令时直接在参数后指定迁移文件名即可,生成路径会自动读取数据源里的migrations配置。

内容的提问来源于stack exchange,提问作者Lucas Mikó

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 07:06:47