Typescript+TypeORM编译后报Cannot use import statement错误问询
解决方案
1. 先修正tsconfig.json编译范围
你当前的include配置仅匹配src和db目录下的一级文件,子目录内的实体、迁移文件不会被编译到build目录,导致运行时TypeORM找不到编译后的JS文件,只能尝试加载源TS文件触发语法报错,修改配置如下:
{ "compilerOptions": { "baseUrl": ".", "target": "es6", "module": "CommonJS", "allowJs": false, "esModuleInterop": true, "noImplicitAny": true, "resolveJsonModule": true, "outDir": "./build", "strict": true, "emitDecoratorMetadata": true, "experimentalDecorators": true }, "include": ["./src/**/*", "./db/**/*"], // 新增**匹配所有子目录文件 "exclude": ["./**/__tests__/*", "./**/__functionaltests__/*"] }
2. 修复ORM配置的路径匹配规则
在config.ts顶部引入path模块,基于__dirname拼接绝对路径,同时区分运行环境匹配对应后缀的文件,避免生产环境加载TS文件:
import * as path from 'path'; const isProd = process.env.NODE_ENV === 'production'; const fileSuffix = isProd ? 'js' : 'ts'; export = { type: 'postgres', host: POSTGRES_HOST, port: POSTGRES_PORT, username: POSTGRES_USER, password: POSTGRES_PASS, database: POSTGRES_DB, synchronize: true, logging: false, // 按环境匹配实体文件 entities: [path.join(__dirname, '../../src/**/*entity.' + fileSuffix)], // 按环境匹配迁移文件 migrations: [path.join(__dirname, '../migrations/*.' + fileSuffix)], cli: { entitiesDir: 'src/entity', migrationsDir: 'db/migrations', }, namingStrategy: new SnakeNamingStrategy(), };
路径计算逻辑基于config.ts的位置:
- 开发运行TS时
__dirname对应root/db/connection,向上跳转两层即可定位到项目根目录 - 生产运行编译后JS时
__dirname对应root/build/db/connection,向上跳转两层也能定位到项目根目录
3. 调整生产启动命令
运行编译后代码时指定生产环境变量,避免匹配TS文件:
NODE_ENV=production node build/db/connection/index.js
内容的提问来源于stack exchange,提问作者Ilias Mentz
相关产品推荐
相关产品推荐

