NestJS + TypeORM 0.3.17迁移文件路径与命名配置问题求助
TypeORM 0.3.17 迁移文件生成路径与命名配置问题
问题概述
使用NestJS结合TypeORM 0.3.17开发时,迁移文件的SQL内容正确,但生成路径和命名不符合预期:
- 原命令带
$npm_config_name时,可在src/migrations下生成{timestamp}-$npm_config_name格式的文件 - 移除该变量后,文件会生成在
src目录,命名为{timestamp}-migrations
期望实现:执行npm run migration:generate {name}即可在src/migrations目录下生成{timestamp}-{name}格式的迁移文件。
当前配置
package.json 命令
"migration:generate": "npm run typeorm migration:generate -- -d src/datasource src/migrations/"
数据源配置(src/datasource.ts)
import { DataSource } from 'typeorm'; export const PostgresDataSource = new DataSource({ type: 'postgres', host: '...', port: 5432, username: '...', password: '...', database: '...', entities: ['src/entities/*.entity.ts'], migrations: ['src/migrations/*.ts'], }); PostgresDataSource.initialize() .then(() => { console.log('Datasource init'); }) .catch((err) => { console.error('Error during Data Source initialization', err); });
解决方案
针对TypeORM 0.3.17版本,通过调整package.json中的命令,支持直接传递迁移名称参数:
方案1:使用npm配置变量(跨shell兼容)
修改package.json中的命令为:
"migration:generate": "npm run typeorm migration:generate -- -d src/datasource src/migrations/$npm_config_name"
执行命令时通过--name指定迁移名称:
npm run migration:generate --name=add-user-table
生成的文件路径为src/migrations/{timestamp}-add-user-table.ts。
方案2:直接传递位置参数(bash/zsh环境)
修改package.json中的命令为:
"migration:generate": "npm run typeorm migration:generate -- -d src/datasource src/migrations/$1"
执行命令时需在名称前加--(用于npm传递参数到脚本):
npm run migration:generate -- add-user-table
注意事项
- Windows Cmd/PowerShell环境需将
$1替换为%1,或使用cross-env包实现跨平台兼容 - 确保
src/migrations目录已存在,TypeORM不会自动创建目录(若不存在需手动创建)
验证
执行命令后,检查src/migrations目录下是否生成了符合{timestamp}-{name}.ts格式的文件,同时确认文件内的SQL迁移逻辑正确。
内容的提问来源于stack exchange,提问作者Sylent
相关产品推荐
相关产品推荐

