NESTJS中的TypeORM实体-无法在模块外部使用import语句 [英] TypeORM Entity in NESTJS - Cannot use import statement outside a module
问题描述
使用嵌套新"命令启动新项目.正常工作,直到我向其中添加实体文件为止.
Started new project with 'nest new' command. Works fine until I add entity file to it.
出现以下错误:
从"typeorm"导入{实体,列,PrimaryGeneratedColumn};
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
^^^^^^^
SyntaxError:无法在模块外部使用import语句
SyntaxError: Cannot use import statement outside a 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:
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 {}
推荐答案
我的假设是您有一个TypeormModule
配置,该配置具有如下所示的entities
属性:
My assumption is that you have a TypeormModule
configuration with an entities
property that looks like this:
entities: ['src/**/*.entity.{ts,js}']
或喜欢
entities: ['../**/*.entity.{ts,js}']
您收到的错误是因为您试图在js
上下文中导入ts
文件.只要您不使用webpack,就可以使用它来获取正确的文件
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}`)]
其中,join
是从path
模块导入的.现在,__dirname
将解析为src
或dist
,然后分别找到所需的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.
以上内容假设配置是通过javascript兼容文件完成的(.js
或在TypeormModule.forRoot()
中传递的参数).如果您使用的是ormconfig.json
,则应使用
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']
,以便您使用已编译的js文件,而没有机会在代码中使用ts文件.
so that you are using the compiled js files and have no chance to use the ts files in your code.
这篇关于NESTJS中的TypeORM实体-无法在模块外部使用import语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!