TypeORM如何配置可同时适配运行时JS路径与CLI免编译调用TS路径?
TypeORM 动态路径适配方案
你提出的基于运行环境判断切换路径的方案完全可行,是这类场景的通用实现方式。
实现方式
方案1:基于运行文件后缀自动判断(无需额外配置)
通过判断当前执行文件的后缀区分是否为编译后运行状态,逻辑最省心:
// ormconfig.ts 配置文件 // CommonJS 规范下直接使用 __filename const isTranspiled = __filename.endsWith('.js'); // ESM 规范下需要先获取 __filename // import { fileURLToPath } from 'url'; // const __filename = fileURLToPath(import.meta.url); // const isTranspiled = __filename.endsWith('.js'); export default { // 其余数据库连接配置保持不变,如 type、host、port、username 等 subscribers: isTranspiled ? ['build/subscriber/*.js'] : ['src/subscriber/*.ts'], migrations: isTranspiled ? ['build/migration/*.js'] : ['src/migration/*.ts'], // 同步修改CLI生成文件的目标路径 cli: { migrationsDir: isTranspiled ? 'build/migration' : 'src/migration', subscribersDir: isTranspiled ? 'build/subscriber' : 'src/subscriber', } }
方案2:基于环境变量手动控制(可控性更高)
适合需要强制指定运行模式的场景,执行CLI前添加环境变量即可:
# 本地执行CLI命令示例(Windows 可使用 cross-env 兼容环境变量设置) TYPEORM_USE_TS=true ts-node ./node_modules/typeorm/cli.js migration:generate
配置文件逻辑:
const isTranspiled = process.env.TYPEORM_USE_TS !== 'true'; export default { // 其余配置同上 subscribers: isTranspiled ? ['build/subscriber/*.js'] : ['src/subscriber/*.ts'], migrations: isTranspiled ? ['build/migration/*.js'] : ['src/migration/*.ts'], }
注意事项
- 本地使用ts-node执行TypeORM CLI时,需要确保tsconfig.json开启
esModuleInterop: true配置,避免模块导入报错 - 不要在编译后的build目录下存放业务源码,避免路径判断出现异常
内容的提问来源于stack exchange,提问作者Kirpich643
相关产品推荐
相关产品推荐

