프로그래밍⚡️/node

tsc, node에서 typescript 실행하기

Kwangkki 2023. 6. 17. 10:40

블로그에 비공개로 밀려있는 글이 꽤 된다. 요즘 공부하는 것들이 쉽게 이해되지 않다 보니 글도 쉽게 마무리되지 않고 있다.

그래도 오늘은 비교적 가벼운 주제로 글을 써본다.

node에서 typescript가 실행되지 않는다?

문제의 발단은 다음과 같다. namespace와 module의 차이점, 스코프에 대해 이것 저것 테스트해본 코드다.

//index.ts
const a = "aaaa";

namespace test {
  export const b = "bbb";
  console.log(b);
}

console.log(test.b);
console.log(a);

 

index.ts에 코드를 작성 후 node로 결과를 보기 위해 터미널에 node index.ts를 쳤는데 아래와 같은 에러가 떴다.

 

SyntaxError: Unexpected identifier

 

대문자 Test로도 해보고 console의 문제가 인가 싶어 여러모로 수정했지만 여전히 되지 않는다.

 

알고보니 node는 타입스크립트를 읽지 못한다.
그래서 따로 컴파일러을 해줘야 한다.

 

tsc

node에서 타입스크립트 코드를 컴파일러하는 라이브러리 중 ts-node가 있다. ts파일을 js로 변환 후 실행하는 기능을 제공한다.

https://www.npmjs.com/package/ts-node

 

ts-node

TypeScript execution environment and REPL for node.js, with source map support. Latest version: 10.9.1, last published: a year ago. Start using ts-node in your project by running `npm i ts-node`. There are 8345 other projects in the npm registry using ts-n

www.npmjs.com

 

라이브러리를 install 후에는 터미널에서 아래와 같은 명령어로 node를 실행할 수 있다고 한다.

 

# Execute a script as `node` + `tsc`.
ts-node script.ts

# Starts a TypeScript REPL.
ts-node

# Execute code with TypeScript.
ts-node -e 'console.log("Hello, world!")'

# Execute, and print, code with TypeScript.
ts-node -p -e '"Hello, world!"'

# Pipe scripts to execute with TypeScript.
echo 'console.log("Hello, world!")' | ts-node

# Equivalent to ts-node --transpileOnly
ts-node-transpile-only script.ts

# Equivalent to ts-node --cwdMode
ts-node-cwd script.ts

# Equivalent to ts-node --esm
ts-node-esm script.ts

 

ts-node 실행 에러

다만, 설치 후 터미널에 ts-node로 실행하면 command를 찾을 수 없다는 에러가 계속 발생한다.

ts-node index.ts
--
zsh: command not found: ts-node
FAIL: 127

 

아마 내가 ts-node를 글로벌에 설치하기 싫어서 dev로 설치해서 생긴 문제인 것 같았다.

위 문제를 해결하기 위한 방법은 많은데 일단 내가 시도 해본 방법은 2가지가 있다.

npx 실행

npx는 npm 저장소에서 패키지를 찾아 직접 실행할 수 있다고 한다.

그래서 아래와 같이 npx로 실행하면 정상적으로 출력이 된다.

 

npx ts-node ./index.ts

scrpits 명령어로 실행

package.json에 스크립트를 추가해서 실행하면 된다.

//pakage.json

"scripts": {
    "start": "ts-node index.ts"
  },

스크립트 추가 후 npm start로 실행하면 성공!

 

 

추가로

npx tsc ./index.ts

명령어를 치면 index.js 파일이 생성되고 자바스크립트로 변환된 코드도 볼 수 있다. 신기방기

// index.js

var a = "aaaa";
var test;
(function (test) {
    test.b = "bbb";
    console.log(test.b);
})(test || (test = {}));
console.log(test.b);
console.log(a);

좀 특이한데, test를 변수로 지정하고 IIFE 개념으로 실행하는 거라 한다.