TypeScript 에서 컴파일하면 const 가 var 가 되는 이유 (feat. tsconfig.json)

해리포터·2022년 11월 10일
0
post-thumbnail

TypeScript를 공부하던 중에, ts 파일을 js로 컴파일하면 const 로 선언한 것이 var 로 바뀌어 있다는 사실을 알게 되었다.

JavaScript 공부할때 var 쓰지 말라고 그랬는데 아니 왜 constvar로 바뀌는 건지, 도대체 왜..?

역시나 정답은 공식문서에 있었다.

Modern browsers support all ES6 features, so ES6 is a good choice. You might choose to set a lower target if your code is deployed to older environments, or a higher target if your code is guaranteed to run in newer environments.
The target setting changes which JS features are downleveled and which are left intact. For example, an arrow function () => this will be turned into an equivalent function expression if target is ES5 or lower.

컴파일 할 때 default가 ES3로 되어있어서 var로 바뀌었던 것이다!!
(참고: const는 ES6에서 새로 도입되었다.)
같은 이유로 화살표 함수 도 컴파일하면 function 키워드로 바뀌어있었을 것이다. Promise 도 적용이 되려면 ES6로 바꿔주어야 한다.


✅ 해결방법

터미널에 아래 명령어를 입력해서 tsconfig.json 파일을 생성한다.
(루트 경로에 수동으로 생성해줘도 된다.)

tsc --init

생성된 tsconfig.json 파일에 다음과 같이 입력한다.

// tsconfig.json
{
	"compilerOptions": {
		"target": "ES2015",
	}
}

targetECMAScript 목표 버전 설정을 할 수 있는 옵션이다.

  • 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018', 'ES2019', 'ES2020', 'ESNEXT'

이 옵션말고도 여러 옵션을 설정해줄 수 있다.

tsconfig.json 세부 설정 방법

참고하기 좋은 레퍼런스들이다.

코딩애플
타입스크립트 핸드북

profile
FE Developer 매일 한 걸음씩!

0개의 댓글