NESTJS中的TypeORM实体-无法在模块外部使用import语句 [英] TypeORM Entity in NESTJS - Cannot use import statement outside a module

查看:1312
本文介绍了NESTJS中的TypeORM实体-无法在模块外部使用import语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用嵌套新"命令启动新项目.正常工作,直到我向其中添加实体文件为止.

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将解析为srcdist,然后分别找到所需的tsjs文件.让我知道是否仍然存在问题.

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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆