通过config.json文件注册时,导入语句破坏了typeorm实体

老丝 · 04月07日

按照官方文档,我创建了小型koa / typeorm / postgres应用。当我createConnection与config 一起使用时,将实体导入同一文件中,应用运行正常,但是typeorm cli无法找到配置文件,因此我尝试将config移至“ ormconfig.json”。现在我得到这个错误:

SyntaxError: Cannot use import statement outside a module

看来typeorm无法使用es6功能。

我的ormconfig.json

{
  "type": "postgres",
  "host": "localhost",
  "port": 5432,
  "username": ****,
  "password": ****,
  "database": ****,
  "synchronize": true,
  "entities": ["src/entity/**/*.ts"],
  "migrations": ["src/migration/**/*.ts"],
  "subscribers": ["src/subscriber/**/*.ts"],
  "cli": {
    "entitiesDir": "src/entity",
    "migrationsDir": "src/migration",
    "subscribersDir": "src/subscriber"
  }
}

我的tsconfig.json

{
  "compilerOptions": {
    "lib": ["es5", "es6"],
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "outDir": "./dist",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
  },
  "exclude": ["node_modules"]
}

出现错误的文件:

import {
  BaseEntity,
  Column,
  Entity,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  ManyToOne
} from 'typeorm';
import { IsIn, IsPositive, IsNotEmpty } from 'class-validator';

import { LOAN_TYPE } from '../consts';
import { User } from './user';

@Entity('loans')
export class Loan extends BaseEntity {
  @PrimaryGeneratedColumn()
  public id: number;

  @CreateDateColumn({ type: 'timestamp' })
  public createdAt: Date;

  @Column()
  @IsNotEmpty()
  @IsPositive()
  public amount: number;

  @Column({ type: 'enum', enum: LOAN_TYPE })
  @IsNotEmpty()
  @IsIn(Object.values(LOAN_TYPE))
  public type: LOAN_TYPE;

  @Column({ default: false })
  public approvalStatus: boolean;

  @ManyToOne(type => User, user => user.loans)
  @IsNotEmpty()
  public user: User;
}

export default Loan;

回答(2)
时间
理查德
2 · 2020-04-07 18:53:36
  1. 请确保您有"module": "commonjs""compilerOptions"tsconfig.json
  2. 使用ts-node运行typeorm cli: ts-node ./node_modules/typeorm/cli.js

查看文件

小小
1 · 2020-04-07 18:53:36

尝试运行CLI或运行应用程序时出现错误?

您可能需要更改"entities"的条目ormconfig.json["dist/entity/**/*.js"]"entitiesDir""dist/entity"

你的回答

加载中...
⌘+Return 发表
发表

温馨提示:登录后可发表评论或回复

关闭,朕知道了

扫码关注微信公众号或小程序