타입스크립트로 작성된 파일을 Node.js에서 실행시키려면 ts-node를 통해 파일을 실행시켜야 한다.
$ npm i ts-node
$ ts-node index.ts
여기에 tsconfig에서 paths를 통해 절대경로를 설정한다면 tsconfig-paths를 추가로 설치해서 ts-node를 실행할 때 옵션을 추가해줘야 한다.
$ npm i -D tsconfig-paths
$ ts-node -r tsconfig-paths/register index.ts
nodemon으로 타입스크립트 파일이 변경될 때마다 재시작하려면 실행 명령어를 아래와 같이 하면 된다.
$ nodemon --exec ts-node -r tsconfig-paths/register index.ts
여기에 import, export를 사용하는 ES모듈을 사용하려면 tsconfig에서 esModuleInterop을 true로, module을 CommonJS로 설정해준다.
{
"compilerOptions": {
"target": "ESNext",
"esModuleInterop": true,
"module": "CommonJS",
"moduleResolution": "Node"
}
}
만약 아래와 같은 문구로 에러가 뜬다면, 특정 라이브러리에서 require문이 사용되고 있는 것이다.
return old(m, filename);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module [오류가 난 라이브러리 파일 경로] from [오류가 난 파일 경로] not supported. Instead change the require of index.js in [오류가 난 파일 경로] to a dynamic import() which is available in all CommonJS modules. at Object.require.extensions.
대표적으로 node-fetch의 경우 2버전으로, nanoid의 경우 3.3.4버전으로 다운그레이드하면 해결된다.
참고자료
https://chanyeong.com/blog/post/35
타입스크립트에서 절대경로(alias) 사용하기! :: chanyeong
개요 요즘 부스트캠프에서 프로젝트를 진행하고 있는데 서버를 타입스크립트로 구현하고 있다. 그런데 설계 과정에서 폴더 및 파일이 나눠지고 import, export하는 과정에서 상대경로를 사용하다
chanyeong.com
[NodeJS] node-fetch 에러 해결 - Error [ERR_REQUIRE_ESM]: require() of ES Module ~ from ~ not supported.
fetch를 추가하자 아래와 같은 에러가 발생했다.검색을 해보니 방법이 두가지 있는 것 같았다.1\. node-fetch 삭제 후 v2로 재다운로드2\. package.json의 타입 변경npm uninstall node-fetchnpm install node-fetc
velog.io
https://github.com/ai/nanoid/issues/365
v4 can't be imported in node · Issue #365 · ai/nanoid
Hello, I'm not knowledgeable at all in all the module formats / import mess of javascript / node, but I'm using KeystoneJS and I import nanoid in it. Since version 4 (2 days ago), I have th...
github.com
'IT > TypeScript' 카테고리의 다른 글
[TS] const assertion (as const) (0) | 2022.08.01 |
---|---|
[TS] CRA에서 tsconfig paths로 절대경로 설정하기 (react-app-alias) (0) | 2022.07.20 |
[TS] TypeScript가 SVG 파일을 import하지 못하여 에러가 발생할 때 (0) | 2022.06.30 |
[TS/Webpack/Jest] tsconfig paths를 사용할 때 Webpack, Jest 설정하기 (0) | 2022.06.27 |