Nest에서 TypeORM을 연결해서 사용을 시도하였었다.
하지만 npm script에 자동으로 생성되는 npm run start:dev로 실행을 하자 아래와 같은 에러가 발생되었다.
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
^^^^^^
typeorm syntaxerror: cannot use import statement outside a module
기본적으로 typescript가 정상적으로 컨버트가 안되는것이 원인으로 생각이 되었고, 해법을 찾아야 했다.
먼저, 위의 에러로 검색을 해보니 똑같은 증상을 가지고 있는 stackoverflow의 글을 찾을수 있었다.
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. Got following error: import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm'; ^^^^^^
stackoverflow.com
위의 링크에서 소개하고 있는 가장 추천이 높은 해법은 아래와 같다
My assumption is that you have a
TypeormModule
configuration with anentities
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 ajs
context. So long as you aren't using webpack you can use this instead so that you get the correct filesentities: [join(__dirname, '**', '*.entity.{ts,js}')]
하지만, 위의 3가지 방법 모두 시도해보았지만 실패하였다.
그러던와중 두번째 답변에서 눈에 띄는것이 있었다
typeorm": "ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli.js"
위에서 tsconfig-paths/register 라는 모듈을 발견을 하게 되었고, 참고하고 있는 example소스에서도 사용하고
있다는것을 할게 되었다.
tsconfig-paths
Load node modules according to tsconfig paths, in run-time or via API.
www.npmjs.com
따라서 nodemon과 함께 사용하기로 했다.
{
"watch": ["src"],
"ext": "ts",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node -r tsconfig-paths/register src/main.ts"
}
위와 같이 실행 코드를 적용하고, script에는 "start:dev": "nodemon"
으로 바꿔 놓았다.
위와 같이 적용하니 정상적으로 import되어서 만들어 놓은 entity에 따라 DB가 구성되었다!
저 같은 경우, 개발 DB와 실제 DB 설정이 entities 설정이 달라서 로컬에선 문제가 없었는데 도커에선 자꾸 import 오류가 발생하여, 도커에서 계속 문제를 찾고 있었는데 이 글 덕분에 DB 설정 파일을 다시 살펴보고 간단히 해결할 수 있었습니다. 정말 감사합니다.
저 같은 경우, entities 속성을 아예 없애니 제대로 동작했습니다.
이제 비슷한 오류가 생기면, DB에서 entities 설정을 잘못했구나. 라고 알 수 있을 듯 합니다.
도커 이미지에서 노드 버전을 바꿔보고, yarn에서 npm으로 바꾸고 온갖 설정을 추가하고 package.json에서 module을 추가하고 온갖.... 시도를 다하다가 이 글보고 겨우 해결하니 댓글을 안달 수가 없네요.
감사합니다!