-
TSC vs BabelComputer Science/TypeScript 2023. 9. 15. 16:18
1. TypeScript 란
2. tsc 란
3. Babel 이란
4. tsc vs babel
5. tsc 사용법
6. babel 사용법
TypeScript란
TypeScript는 JavaScript의 Superset으로 기존 JavaScript문법에서 정적 타입 시스템을 추가한 것으로 코드의 안정성과 가독성을 향상시킨다. 다면 결과적으로 실행되는 코드는 JavaScript이기에 TypeScript 문법에서 JavaScript문법으로 변환되는 과정이 필요하다. 이 과정에서 크게 2가지가 사용 되는데 tsc와 @babel/preset-typescript 이다.
TSC 란tsc는 TypeScript를 JavaScript로 변환시키는 명령어로 TypeScript Compiler 라고 할 수 있다.
현재 tsc가 JavaScript로 변환해주는 default 버전은 ES3이라고 한다. ( 2023.09.15 )
https://www.typescriptlang.org/tsconfig#targetBabel 이란 ( @babel/preset-typescript )
Babel은 최신 버전의 JavaScript 코드를 구 버전으로 변환할 때 자주 사용되는 오픈소스 JavaScript 컴파일러이다. 다양한 플러그인과 프리셋 확장성을 가지고 있으며 그중 typescript에 해당하는 프리셋이 @babel/preset-typescript이다.
TSC vs Babel
TSC 의 장점
Babel은 컴파일시 type checking을 하지 않는다 하지만 tsc는 type checking을 하여 오류 발생시 compile하지 않는다.
Babel의 장점확장성. 다른 Babel plugin들을 적용할 수 있다. Babel은 TypeScript의 타입을 체크하지 않고 그저 삭제하니 컴파일이 더 빠르다. Babel이 TypeScript의 'const enum' 등을 지원하지 못한다는것은 Babel의 7.16 버전 이전 이야기이다. 현재는 전부 지원된다.
결론
기타 Babel의 Plugin등을 사용하지 않는다면 tsc만을 사용하는 것은 좋은 해결책이다. 다만 프로젝트가 커지고 사용할 일이 생긴다면 tsc는 타입 체크 용도로면 사용하며 babel 을 많이 사용한다. tsc --noEmit 명령어를 통해 타입체크만 할 수 있다.
TSC 사용법
TypeScript를 설치해준다.
npm install typescript --save-dev
tsc 의 각종 compile option 은 여기서 확인할 수 있다.
https://www.typescriptlang.org/docs/handbook/compiler-options.html
명령줄에 입력 파일을 직접 지정하지 않는다면 tsc는 tsconfig.json을 참고하여 컴파일을 하고 직접 지정한다면 tsconfig.json을 무시한다. tsconfig.json을 쉽게 만들고 싶다면
tsc --init
명령어를 입력하면된다.
typescript 5.2.2 버전 기준으로 tsconfig.json을 만들면 target이 es2016으로 생성해준다.https://www.typescriptlang.org/tsconfig#target
여기서도 나오듯이 ES6가 좋은 선택지라고 나온다. ES6(es2015) 와 es2016은 큰차이가 없는데 불안하다면 es6 혹은 es5로 변동하자.
tsconfig.json에"compilerOptions": { ..., #tsc --noEmit "noEmit": true }
를 추가한다면 tsc --noEmit과 같은 효과를 볼 수 있다.
Babel 사용법
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/preset-typescript
root ( package.json 이 위치한 곳 ) 에 babel.config.json을 만들어준다
{ "presets": [ [ "@babel/preset-env", { "targets": { "edge": "17", "firefox": "60", "chrome": "67", "safari": "11.1" }, "useBuiltIns": "usage", "corejs": "3.6.5" } ], "@babel/preset-typescript" ] }
이런뒤 package.json의 script에 babel을 추가해주고
"scripts": { "start": "node index.js", "babel": "npx babel index.ts --out-file index.js", "test": "echo \"Error: no test specified\" && exit 1" }
npm run babel하면 ts 파일이 js파일로 변경된것을 확인할 수 있다.
"scripts": { "start": "node index.js", "babel": "npx babel index.ts --out-file index.js", "build": "tsc && npm run babel", "test": "echo \"Error: no test specified\" && exit 1" }
이렇게 tsc로는 type check만 하고 build는 babel로 할 수 있다.
'Computer Science > TypeScript' 카테고리의 다른 글
[TypeScript] Declare 의 용도 (0) 2023.11.19 Utility Types ( Partial, Required, Pick&Omit ) (0) 2023.10.21 Template Literal Type (0) 2023.10.14 infer (1) 2023.09.30 type vs interface (0) 2023.09.22