[typescript] express에서 ts-node로 실행 시 global type 못 찾는 에러

codeing999·2023년 9월 21일
1

TypeScript

목록 보기
3/3

문제

내 프로젝트의
./src/types/index.d.ts 를 만든 후,

d는 delcare의 d를 뜻한다고 한다.
이 때 타입을 delcare하는 파일의 디렉토리명이나 .d.ts라는 확장자를 제외한 파일명이 무엇인지는 강제되지 않는다고 한다.
tsconfig.json에 제대로 써주기만 하면 된다.

declare global {
  interface jwtToken {
    userInfo: number;
  }
}

이와 같이 글로벌 타입을 declare하였다.

tsconfig.json에는 다음과 같이

"typeRoots": ["node_modules/@types", "src/types"],

typeRoots에 명시해주었다.

그런데도,

cross-env NODE_ENV=beta ts-node -r tsconfig-paths/register ./src/index.ts

이와 같은 커맨드로 실행하려고 하면 내가 declare한 global type을 찾지 못한다는 에러가 났다.
코딩하는 단계에서는 에러가 안나고 사용이 되는 type이었다.

이에 대해 gpt나 여러 검색을 해보았고 심지어 typescript 공식문서도 보았지만 원인을 발견하지 못했다.

"include": ["src/**/*"],

이러한 설정도 분명히 했기에 해당 .d.ts파일이 읽혔어야 한다.
그리고 ts-node가 아닌 tsc로 컴파일 할 때는 에러가 안나고 js파일 자체로 실행까지도 잘된다.

해결

ts-node가 단순 패키지 페이지만 있는게 아니라
https://www.npmjs.com/package/ts-node
https://typestrong.org/ts-node/docs/
이러한 꽤나 자세한 docs 페이지가 있는 걸 발견하고 여기를 읽어보니 답이 나왔다.

https://typestrong.org/ts-node/docs/
이 부분을 보면
타입을 찾지 못하는 트러블 슈팅을 다루는데,
이러이러한 설정들을 했는데도 그래도 안된다면


이러한 옵션을 주면 해결될 것이라 설명하였고, 이렇게 하니 실제로 되었다.
이 옵션은 defalut가 false여서
내가 tsconfig.json에서 설정한 include, files, exclude 옵션을 보지 않는다고 한다.

이 옵션을 주니 해결이 되었다.

추가로
아예 해당 옵션을 tsconfig.json에 명시하고 명령어에선 생략할 수도 있다.

{
  "compilerOptions": {
	...
  },
  "ts-node": {
    "files": true
  }
}

추가

tsc --traceResolution

이 명령어를 쓰면 모듈레졸루션 과정을 자세히 보여준다고 한다.

The tsc --traceResolution command is used to trace and display detailed information about how TypeScript resolves module imports and type references. When you run this command, TypeScript will provide a detailed log of its module resolution process, including the paths it searches for modules, the extensions it considers, and the results of the resolution.

This can be helpful for diagnosing issues related to module resolution, especially when you encounter problems with import statements or type references in your TypeScript code. The trace information can show you the steps TypeScript takes to locate and load modules or types, which can be useful for debugging and understanding the module resolution process.

Here's an example of how to use the tsc --traceResolution command:

tsc --traceResolution

After running this command, TypeScript will display detailed information about module resolution as it processes your TypeScript files. This can be especially useful when you're working with complex project setups or encountering unexpected module resolution behavior.

profile
코딩 공부 ing..

0개의 댓글