npmnestjs95% confidence\u2191 150

TypeORM Entity in NESTJS - Cannot use import statement outside a module

Full error message
Started new project with 'nest new' command. Works fine until I add entity file to it.

Got following error:

  import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

  
  ^^^^^^

  
  SyntaxError: Cannot use import statement outside a module

What do I miss?

Adding Entity to Module:

import { Module } from '@nestjs/common';
import { BooksController } from './books.controller';
import { BooksService } from './books.service';
import { BookEntity } from './book.entity';
import { TypeOrmModule } from '@nestjs/typeorm';

@Module({
  imports: [TypeOrmModule.forFeature([BookEntity])],
  controllers: [BooksController],
  providers: [BooksService],
})
export class BooksModule {}

app.module.ts:

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { BooksModule } from './books/books.module';

@Module({
  imports: [TypeOrmModule.forRoot()],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

My assumption is that you have a TypeormModule configuration with an entities property that looks like this: entities: ['src/**/*.entity.{ts,js}'] or like entities: ['../**/*.entity.{ts,js}'] The error you are getting is because you are attempting to import a ts file in a js context. So long as you aren't using webpack you can use this instead so that you get the correct files entities: [join(__dirname, '**', '*.entity.{ts,js}')] where join is imported from the path module. Now __dirname will resolve to src or dist and then find the expected ts or js file respectively. let me know if there is still an issue going on. EDIT 1/10/2020 The above assumes the configuration is done is a javascript compatible file (.js or in the TypeormModule.forRoot() passed parameters). If you are using an ormconfig.json instead, you should use entities: ["dist/**/*.entity.js"] so that you are using the compiled js files and have no chance to use the ts files in your code. Or use autoLoadEntities: true,

API access

Get this solution programmatically \u2014 free, no authentication.

curl https://depscope.dev/api/error/f327920e8d2209b14ec7d864b216613d2465df80390c1e2911955f4258e79603
hash \u00b7 f327920e8d2209b14ec7d864b216613d2465df80390c1e2911955f4258e79603
TypeORM Entity in NESTJS - Cannot use import statement outsi… — DepScope fix | DepScope