Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import statement breaks typeorm enitities when registered through config.json file

Following official docs, I created small koa/typeorm/postgres app. When I was using createConnection with config, importing entities in the same file, app was working fine, but typeorm cli coudn't find config file so I tried moving config to "ormconfig.json". Now I get this error:

SyntaxError: Cannot use import statement outside a module

It looks as if typeorm isn't able to use es6 features.

My 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"
  }
}

My tsconfig.json:

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

File with error:

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;

like image 592
vvAve Avatar asked Oct 23 '19 19:10

vvAve


2 Answers

  1. Make sure you have "module": "commonjs" in "compilerOptions" of tsconfig.json
  2. Run typeorm cli using ts-node: ts-node ./node_modules/typeorm/cli.js

See docs

like image 114
Joseph Buchma Avatar answered Sep 21 '22 15:09

Joseph Buchma


Are you getting the error when trying to run the CLI, or when running the app?

You may need to change the "entities" entry in ormconfig.json to ["dist/entity/**/*.js"] or the "entitiesDir" to "dist/entity".

like image 37
Robfz Avatar answered Sep 19 '22 15:09

Robfz