Language/Typescript

Typescript 컴파일 설정

쓰링 2022. 11. 9. 12:31
반응형

Javascript를 Typescript 전환하는 방법

  • 비주얼 스튜디오 코드(VSCode)로 자바스크립트 페어링
  • 자바스크립트용 타입스크립트 컴파일러 사용
  • 자바스크립트 파일을 타입스크립트 파일로 변환
  • 엄격한 타입 체크
Compilation Context
기본적으로 TypeScript 가 어떤 것이 유효하고 어떤 것이 유효하지 않은지 결정하기 위한 용어
컴파일 컨텍스트에는 어떤 파일에 대한 정보와 함께 어떤 컴파일러 옵션을 사용하는지에 대한 정보가 포함

 

Typescript 컴파일

tsconfig.json

  • 명령어를 매번 입력하지 않고 컴파일 설정 파일 생성하여 사용
  • TypeScript 프로젝트의 루트 디렉토리(Root Directory)에 위치
  • tsconfig.json사용할 경우
    • 인풋 파일이 없는 tsc 명령 : tsconfig.json에 설정된 모든 디렉토리를 체인하여 컴파일
    • 인풋 파일이 없는 tsc 명령 : -p 옵션 사용, 특정 디렉토리 내에 있는 tsconfig.json or 유효한 JSON파일 설정
  • tsconfig.json 사용하지 않을 경우
    • 인풋 파일이 있는 tsc <파일.ts> 명령일 경우, tsconfig.json 파일 무시
    • tsconfig.json파일 내 설정된 컴파일 옵션보다 명령어가 우선

tsconfig.json 생성

$ tsc --init
  • 최상위 프로퍼티 8개
    1. compileOnSave
    2. extends
    3. compileOptions
    4. files
    5. include
    6. exclude
    7. references
    8. typeAcquisition
{
	"compileOnSave": true,
	"extends": "path",
	"compilerOptions": {...},
	"files": [...],
	"include": [...],
	"exclude": [...],
	"references": [...],
	"typeAcquisition": 
}

 

tsconfig.json 옵션

files

  • 설정 없으면 컴파일
  • 상대 혹은 절대 경로의 리스트 배열
  • exclude 보다 강력
{
	...
	"filesDefinition": {
    "properties": {
      "files": {
        "description": "If no 'files' or 'include' property is present in a tsconfig.json, the compiler defaults to including all files in the containing directory and subdirectories except those specified by 'exclude'. When a 'files' property is specified, only those files and those specified by 'include' are included.",
        "type": "array",
        "items": {
          "type": "string"
        }
      }
    }
  }
	...
}

 

include / exclude

  • 컴파일에 포함/제외할 디렉토리/파일 경로를 설정
  • 포함, 제외될 각 항목에 glob 패턴 사용
    • * 0 이상의 모든 문자와 일치 (디렉토리 분리 기호 제외)
    • ? 1개 문자와 일치 (디렉토리 분리 기호 제외)
    • **/ 모든 하위 디렉토리까지 포함
  • include
    • exclude보다 약함
    • * 를 사용하면, .ts / .tsx / .d.ts 만 include (allowJS)
  • exclude
    • 설정 없으면 4가지(node_modules, bower_components, jspm_packages, <outDir>)를 default로 제외
    • <outDir> 은 항상 제외
{
  // 컴파일 포함
  "include": [
    "src/**/*.tsx?"
  ],
  // 컴파일 제외
  "exclude": [
    "node_modules",
    "build",
    "**/*.(spec|test).ts"
  ],
  // 컴파일 옵션
  "compilerOptions": { ... }
}

 

compileOnSave

  • true / false (default false)
  • IDE에 저장할 때마다 컴파일 수행하도록 signal 전송
더보기

지원되는 IDE

  • Visual Studio 2015 with TypeScript 1.8.4 이상
  • atom-typescript 플러그인
{
	...
	"compileOnSaveDefinition": {
    "properties": {
      "compileOnSave": {
        "description": "Enable Compile-on-Save for this project.",
        "type": "boolean"
      }
    }
  },
	...
}

 

typeRoots, types

  • typeRoots
    • 배열로 설정하며 기본값은 ["node_modules/@types"]
    • typescript가 정의돼 있는 type을 찾는 공간
    • 경로는 tsconfig.json이 있는곳에서 부터 상대 경로로 작성
    • 지정한 type 경로는 외부 라이브러리가 제공하는 모듈 타입 정의를 위해 사용
  • types

 

{
	...
  "typeRoots": {
		"description": "Specify list of directories for type definition files to be included. Requires TypeScript version 2.0 or later.",
    "type": "array",
    "items": {
	    "type": "string"
    }
  },
  "types": {
	  "description": "Type declaration files to be included in compilation. Requires TypeScript version 2.0 or later.",
    "type": "array",
    "items": {
	    "type": "string"
    }
  }
	...
}
 

 

 

@types

  • TypeScript 2.0 부터 사용 가능한 내장 type definition 시스템
  • 설정이 없으면 node_modules/@types라는 모든 경로를 찾아서 사용

typeRoots를 사용하는 경우

  • 배열 안에 들어있는 경로 하위에서만 가져옴
  • typeRoots와 types 같이 사용 X

typeRoots를 사용하는 경우

  • 배열 안의 모듈 or ./node_modules/@types/ 안의 모듈에서 찾아옴
  • [] 빈 배열을 넣는것 = 이용하지 않겠다
  • typeRoots와 types 같이 사용 X

 

target과 lib

target

  • 빌드 결과물 버전 설정
  • defalut 값 es3

lib

  • 기본 type definition 라이브러리 설정
  • defalut 값
    • target 이 'es3' 이고, 디폴트로 lib.d.ts 사용
    • target 이 'es5' 이면, 디폴트로 dom, es5, scripthost 사용
    • target 이 'es6' 이면, 디폴트로 dom, es6, dom.iterable, scripthost 사용
  • lib를 지정
    • lib 배열로만 라이브러리를 사용
    • 빈 [] ➡ 'no definition found ... '
{
	...
	"target": {
	  "description": "Specify ECMAScript target version. Permitted values are 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018' or 'esnext'.",
    "type": "string",
    "default": "es3",
    "anyOf": [
	    {
	      "enum": [
	        "es3",
          "es5",
          "es6",
          "es2015",
          "es2016",
          "es2017",
          "es2018",
          "esnext"
        ]
      }
			{
	      "pattern": "^([eE][sS]([356]|(201[5678])|[nN][eE][xX][tT]))$"
      }
    ]
  },
  "lib": {
	  "description": "Specify library file to be included in the compilation. Requires TypeScript version 2.0 or later.",
    "type": "array",
    "items": {
    "type": "string",
    "enum": [
			"es5",
			"es6",
			"es2015",
			"es7",
			"es2016",
			"es2017",
			"es2018",
			"esnext",
			"dom",
			"dom.iterable",
			"webworker",
			"scripthost",
      "es2015.core",
			"es2015.collection",
			"es2015.generator",
			"es2015.iterable",
			"es2015.promise",
			"es2015.proxy",
			"es2015.reflect",
			"es2015.symbol",
			"es2015.symbol.wellknown",
			"es2016.array.include",
			"es2017.object",
			"es2017.intl",
			"es2017.sharedmemory",
			"es2017.string",
			"es2017.typedarrays",
			"es2018.intl",
			"es2018.promise",
			"es2018.regexp",
			"esnext.asynciterable",
			"esnext.array",
			"esnext.intl",
			"esnext.symbol"
		]
	},
  ...
}

 

outDir, outFile

  • outDir
    • files include를 통해 선택된 파일들의 결과가 저장되는 디렉터리 지정
  • outFile
    • 모든 파일을 하나의 파일로 합쳐서 출력할 경우 지정
    • module none, system 또는 amd가 아닌 경우 사용 불가
{
	...
  "outFile": {
		"description": "Concatenate and emit output to single file.",
		"type": "string"
	},
	"outDir": {
		"description": "Redirect output structure to the directory.",
		"type": "string"
	},
	...
}

 

noEmit

  • true 설정 시 최종결과물 출력 안됨
  • 단순 타임 체크용으로 사용할 것인지 아니면 tsc를 컴파일용으로 사용할 것인지 지정

 

declaration

  • true 설정 시 해당 .ts 파일의 .d.ts 파일 또한 같이 출력물에 포함

 

emitDeclarationOnly

  • true 설정 시 출력물에 declaration 파일만 나옴

 

sourceMap

  • true 설정 시 출력물에 .js.map 이나 .jsx.map 파일 포함
  • inlineSourceMap을 true로 지정 시 .js 파일 내부에 source map 포함
  • 두 속성 같이 사용 불가

 

module

  • module
    • 컴파일 된 모듈 결과물 설정
    • target 이 'es6'면 디폴트 es6
    • target 이 'es6' 가 아니면 디폴트 commonjs 
    • AMD 나 System과 사용하려면, outFile이 지정
    • ES6 나 ES2015를 사용하려면, target이 es5 이하
  • moduleResolution
    • ts 소스에서 모듈 사용하는 방식 지정
    • Classic 아니면 Node
    • CommonJS 일때만 Node
  • paths와 baseUrl
    • baseUrl로 꼭지점과 paths 안의 키/밸류로 모듈을 가져가는 방식
  • rootDirs
    • 배열 안에서 상대 경로 찾는 방식
{
	...
	"module": {
		"description": "Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015' or 'esnext'.",
		"type": "string",
		"anyOf": [
			{
				"enum": [
					"commonjs",
					"amd",
					"umd",
					"system",
					"es6",
					"es2015",
					"esnext",
					"none"
				]
			},
			{
				"pattern": "^([cC][oO][mM][mM][oO][nN][jJ][sS]|[aAuU][mM][dD]|[sS][yY][sS][tT][eE][mM]|[eE][sS]([356]|(201[567])|[nN][eE][xX][tT])|[nN][oO][nN][eE])$"
			}
		]
	},
	...
}

 

strict

  • 정의해놓은 코드에서 강하게 타입을 정의
  •  default 값 false
  • typescript의 type 검사 옵션 중 strict* 관련된 모든 것 true로 만듬
{
	...
	"strict": {
		"description": "Enable all strict type checking options. Requires TypeScript version 2.3 or later.",
		"type": "boolean"
	},
	...
}

 

 

반응형