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

10,341

Solution 1

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".

Solution 2

  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

Solution 3

Problem is caused not just loading entities, but also for migrations and subscribers.

Your app are looking for entities, migrations and subscribers files on pre-compiled .ts files. So the files contains "imports" not understood by nodejs, it is the cause of your error.

When typescript compile the code it converts all the imports to requires (understood by node).

So to stop error at all you should make your configurations on your ormconfig.json:

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

Related videos on Youtube

vvAve
Author by

vvAve

Updated on June 04, 2022

Comments

  • vvAve
    vvAve almost 2 years

    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;
    
    
  • vvAve
    vvAve over 4 years
    That was it, I figured it out later that night. It was confusing because I was following docs very closely.
  • aizkhaj
    aizkhaj over 4 years
    @robfz: I was just facing the same issue, and know that the proposed solution works, but with my synchronize: true setting, it won't show an updated table for my entity, so I'm trying to point it to src since there must be issues with it on build that's showing up in the dist entity. The question: is there a reason why it doesn't work with src path even though docs show it that way?
  • Joseph Buchma
    Joseph Buchma about 4 years
    Why down vote? Accepted answer is misleading, there is no need to point configuration to dist directory. If your entities are in typescript you should use ts-node to run CLI, as stated in the docs.
  • Ajay
    Ajay almost 4 years
    I second it. The accepted answer is misleading. this is the correct answer! Thanks, @joseph for the correct answer! You saved my time!
  • Vincent
    Vincent almost 4 years
    Totally agree too, during e2e test, it doesn't work, I had to use https://docs.nestjs.com/techniques/database#auto-load-entiti‌​es to autoload entities. Because during test, it's using ts-node transpiling code on the fly (in memory) and the dist directory is not present. So at the end. best option to work in any situation
  • tim
    tim almost 4 years
  • Patrick
    Patrick over 3 years
    having to use the transpiled code in development is an abomination.
  • nburk
    nburk over 3 years
    Side-note: If you don't have ts-node installed globally you can invoke it prefixed with npx, e.g.: npx ts-node ./node_modules/typeorm/cli.js migration:generate -n Init
  • nburk
    nburk over 3 years
    The other answer of invoking the CLI via ts-node seems a bit nicer: npx ts-node ./node_modules/typeorm/cli.js migration:generate -n Init