본문 바로가기

프로그래밍기초/typescript

#02 TypeScript 설치및 컴파일 옵션

# 노드 패키지 설치

npm init


# types node 설치

npm i @types/node

 

# typescript 컴파일러 설치

npm i typescript -g

 

# 타입스크립트 버전확인(설치확인)

tsc -v

 

# 타입스크립트 컴파일

tsc src/index.ts

 

# 실행

node src/index.js

 

# 한방에 타입스크립트를 실행하기

npm i ts-node -g

 

# ts-node 로 실행하기 => node 20 버전 이상에서 더이상 작동안함

ts-node src/index.ts

 

# tsx 설치(ts-node 대체)

npm i -g tsx

# 버전

tsx -v

# 실행

tsx src/index.ts

 

 

컴파일 옵션 (compilerOptions)

1) 초기화

tsc --init

 

 

 

2) target

tsconfig.json

{
  "compilerOptions": {
    "target": "ES5"
  },
  /*컴파일 범위를 지정*/
  "include": ["src"]
}

 

compilerOptions의 target으로 컴파일되는 javascript의 버전을 설정할 수 있다.

 

index.ts

const func = () => console.log("Hello");

 

tsc로 (tsc .\src\index.ts 로 컴파일하면 tsconfig.json이 반영안됨) 컴파일 하면

index.js

var func = function () { return console.log("Hello"); };

 

위와 같이 ES5의 표현식으로 컴파일 된다.

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext" /*최신버전*/
  },
  /*컴파일 범위를 지정*/
  "include": ["src"]
}

 

javascript의 최신버전으로 컴파일 설정후 컴파일하면

index.js

const func = () => console.log("Hello");

 

ES 최신버전의 스타일로 컴파일 된다.

 

3) module

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext" /*최신버전*/,
    "module": "CommonJS"
  },
  /*컴파일 범위를 지정*/
  "include": ["src"]
}

 

module 시스템 설정은 CommonJS, ESNext로 설정할 수 있다.

 

index.ts

import {hello} from './hellow';

hello();

hellow.ts

export const hello = () => {
  console.log("hello");
}

 

위 코드를 CommonJS로 설정후 컴파일 하면

예전 스탈일의 코드로 컴파일 해준다.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const hellow_1 = require("./hellow");
(0, hellow_1.hello)();
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hello = void 0;
const hello = () => {
    console.log("hello");
};
exports.hello = hello;

 

ESNext로 설정후 컴파일하면

import { hello } from './hellow';
hello();
export const hello = () => {
    console.log("hello");
};

 

4) moduleDetection

전역으로 선언한 변수들은 스크립로 인식한다. 스크립트에서 2개의 변수의 이름을 동일하게 하면 에러가 발생한다.

 

index.ts

let a = 1;

 

hello.ts

let a = 1;

 

Cannot redeclare block-scoped variable 'a'.ts(2451)
index.ts(1, 5): 'a' was also declared here.

 

이때, export(); 키워드를 넣어주면 모듈로 인식하기 때문에 에러를 피할수 있는데

let a = 1;
export {};

 

이것을 자동으로 붙여주는 컴파일 옵션이 "moduleDetection" 이다.

 

옵션의 값으로 아래와 같다

옵션값   상황 추천 값
force 전부 모듈로 강제 (현대적, 안전) 최신 프론트엔드 / 번들러, 전역 오염을 절대 허용하면 안 되는 경우
auto 상황 보고 자동 판단 (기본) Node.js ESM
legacy 예전 방식 레거시 TS 프로젝트

 

 

 

 

4) 그밖에..

옵션명 옵션값 설명
outDir dist 컴파일되는 js 위치 설정
strict true / false 엄격한 타입 검사
반응형