타입스크립트 기본설정하기

2023. 4. 18. 17:41JavaScript/Typescript

목차
1. tsc 명령어와 옵션
2. tsconfig.json
2.1 compileOptions
3. ts-node

 

1. tsc 명령어와 옵션

 

지난번에 설치했던 Typescript 컴파일러를 설치해보도록 하자.

 

$ npm init
$ npm install -D typescript

 

타입스크립트 컴파일러를 설치하게되면 tsc 라는 명령어를 사용할 수 있게된다.

 

$ tsc

 

 

tsc 명령어를 사용하게되면 아래와 같이 명령어의 종류와 옵션 사항, 옵션 값들을 볼 수 있다.

 

Version 5.0.4
tsc: The TypeScript Compiler - Version 5.0.4                                                                            
                                                                                                                     TS 
COMMON COMMANDS

  tsc
  Compiles the current project (tsconfig.json in the working directory.)

  tsc app.ts util.ts
  Ignoring tsconfig.json, compiles the specified files with default compiler options.

  tsc -b
  Build a composite project in the working directory.

  tsc --init
  Creates a tsconfig.json with the recommended settings in the working directory.

  tsc -p ./path/to/tsconfig.json
  Compiles the TypeScript project located at the specified path.

  tsc --help --all
  An expanded version of this information, showing all possible compiler options

  tsc --noEmit
  tsc --target esnext
  Compiles the current project, with additional settings.

COMMAND LINE FLAGS

     --help, -h  Print this message.

    --watch, -w  Watch input files.

          --all  Show all compiler options.

  --version, -v  Print the compiler's version.

         --init  Initializes a TypeScript project and creates a tsconfig.json file.

  --project, -p  Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'.

    --build, -b  Build one or more projects and their dependencies, if out of date

   --showConfig  Print the final configuration instead of building.

COMMON COMPILER OPTIONS

               --pretty  Enable color and formatting in TypeScript's output to make compiler errors easier to read.
                  type:  boolean
               default:  true

      --declaration, -d  Generate .d.ts files from TypeScript and JavaScript files in your project.
                  type:  boolean
               default:  `false`, unless `composite` is set

       --declarationMap  Create sourcemaps for d.ts files.
                  type:  boolean
               default:  false

  --emitDeclarationOnly  Only output d.ts files and not JavaScript files.
                  type:  boolean
               default:  false

            --sourceMap  Create source map files for emitted JavaScript files.
                  type:  boolean
               default:  false

           --target, -t  Set the JavaScript language version for emitted JavaScript and include compatible library declarations.
                one of:  es3, es5, es6/es2015, es2016, es2017, es2018, es2019, es2020, es2021, es2022, esnext
               default:  es5

           --module, -m  Specify what module code is generated.
                one of:  none, commonjs, amd, umd, system, es6/es2015, es2020, es2022, esnext, node16, nodenext
               default:  undefined

                  --lib  Specify a set of bundled library declaration files that describe the target runtime environment.
           one or more:  es5, es6/es2015, es7/es2016, es2017, es2018, es2019, es2020, es2021, es2022, es2023, esnext, dom, dom.iterable, webworker, webworker.importscript                         s, webworker.iterable, scripthost, es2015.core, es2015.collection, es2015.generator, es2015.iterable, es2015.promise, es2015.proxy, es2015.reflec                         t, es2015.symbol, es2015.symbol.wellknown, es2016.array.include, es2017.object, es2017.sharedmemory, es2017.string, es2017.intl, es2017.typedarra                         ys, es2018.asyncgenerator, es2018.asynciterable/esnext.asynciterable, es2018.intl, es2018.promise, es2018.regexp, es2019.array, es2019.object, es                         2019.string, es2019.symbol/esnext.symbol, es2019.intl, es2020.bigint/esnext.bigint, es2020.date, es2020.promise, es2020.sharedmemory, es2020.stri                         ng, es2020.symbol.wellknown, es2020.intl, es2020.number, es2021.promise/esnext.promise, es2021.string, es2021.weakref/esnext.weakref, es2021.intl                         , es2022.array, es2022.error, es2022.intl, es2022.object, es2022.sharedmemory, es2022.string/esnext.string, es2022.regexp, es2023.array/esnext.ar                         ray, esnext.intl, decorators, decorators.legacy
               default:  undefined

              --allowJs  Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files.
                  type:  boolean
               default:  false

              --checkJs  Enable error reporting in type-checked JavaScript files.
                  type:  boolean
               default:  false

                  --jsx  Specify what JSX code is generated.
                one of:  preserve, react, react-native, react-jsx, react-jsxdev
               default:  undefined

              --outFile  Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output.

               --outDir  Specify an output folder for all emitted files.

       --removeComments  Disable emitting comments.
                  type:  boolean
               default:  false

               --noEmit  Disable emitting files from a compilation.
                  type:  boolean
               default:  false

               --strict  Enable all strict type-checking options.
                  type:  boolean
               default:  false

                --types  Specify type package names to be included without being referenced in a source file.

      --esModuleInterop  Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility.
                  type:  boolean
               default:  false

You can learn about all of the compiler options at https://aka.ms/tsc

 

위에 있는 옵션 사항을 명령어를 사용할 때마다 적어서 실행해도 되지만,

 

package.json 파일에 미리 어떤 옵션사항을 이용할 지 script 부분에 작성해서 사용할 수도 있다.

 

    "scripts": {
        "build": "tsc --outDir ./dist --target ES6"
    }

 

위와 같이 설정한 뒤 npm 명령어를 사용하면 설정해둔 명령어가 실행된다.

 

$ npm run build
$ tsc --outDir ./dist --target ES6

 

매번 package.json에 들어가서 설정을 해도 되지만,  설정 파일에 설정을 따로 뺴서 사용하는 방법도 있다.

 

tsconfig.json을 작성해보자.

 

{
    "compilerOptions": {
        "target": "ES6",
        "outDir": "./dist"
    }
}

 

이렇게 한뒤 package.json에서 뒤의 옵션들을 지우고 tsc만 남겨서 사용이 가능하다.

 

package.json 안의 tsc 자체가 디폴트로 tsconfig.json라는 파일이 있으면 읽고 옵션을 적용하여 실행하기 때문이다.

 

tsconfig.json이라는 파일을 사용하기도 하고 가끔 다른 설정파일이 필요한 경우도 있다.

 

한 프로젝트 내에서 다른 tsconfig.json이 필요할 때가 있는데, 그 떄에는 --project 옵션을 이용해서 적용시키면 된다.

 

    "scripts": {
        "build": "tsc --project [파일명]"
    }

 

 


2. tsconfig.json

 

tsc 명령어의 옵션을 담아 실행하는 tsconfig.json에 대해서 알아보자.

 

tsconfig는 json 파일로 작성되며 tsc를 실행할 때 적용할 옵션들을 담아놓는 파일이다.

 

위에서 다양한 옵션들을 확인할 수 있었지만, 일반적으로 많이 사용하는 설정들에 대해서 조금 알아보자.

 

{
    "compileOptions": {},
    "include": [],
    "exclude": []
}

 

크게 compileOptions, include, exclude 옵션이 있다.

 

  • compileOptions는 타입스크립트 파일을 컴파일 진행시 어떤 형태로 컴파일 할지 속성을 정의한다.
  • include는 컴파일을 진행할 디렉토리를 지정한다.(간혹 가다가 컴파일을 진행하지 않고 싶을 경우도 존재)
  • exclude는 컴파일을 진행하고 싶지 않을 때 설정하는 속성이다.( test.js와 같은 테스트 파일 등)

 

 

2.1 compileOptions

 

 

자주 사용하는 compileOptions 속성에 대해서 알아보도록 하자.

 

module : " " - 모듈 시스템을 어떤 걸 사용할지 정하는 속성

속성 값 - none, commonjs, amd, umd, system, es6/es2015, es2020, es2022, esnext, node16, nodenext

 

outDir : " " - 어떤 디렉토리에 컴파일을 진행한 파일을 내보낼지 정하는 속성

속성 값에는 내보낼 주소를 적어준다.

 

target : " " - 어떤 자바스크립트 버전으로 번들링을 할 지 정하는 속성

속성 값 - es3, es5, es6/es2015, es2016, es2017, es2018, es2019, es2020, es2021, es2022, esnext

 

esModuleInterop : boolean - import 문법을 바꿀지 지정하는 속성

ex) import * as react from 'react'   →  import react from 'react'

속성 값 -  true, false

 

strict : boolean - 디폴트로  true이며, 이 속성을 지정해야 타입스크립트로서의 기능을 할 수 있다.

속성 값 - true, false

 

위의 속성들은 크게 문제가 없으나, 아래의 속성들은 약간의 추가 설정이 필요하다.

 

baseUrl : " " - 모듈 해석시 상대경로를 해결하기 위해서 default 설정한다.

 

paths : " " - baseUrl을 기준으로 상대 위치를 가져오는 매핑값( 경로를 변수처럼 사용할 수 있다. )

 

 

baseUrl, paths

 

두 속성을 이용하면 모듈을 더 쉽게 import 할 수 있다.

두 속성은 다음과 같은 특징이 있다.

 

  • 타입스크립트를 작성할 때에만 사용이 가능하다.
  • 컴파일하여 사용할 수 있게 만들어 주지는 않는다. (즉, 사용을 위해서 별도의 설정이 필요하다.)

 

$ npm install -D tsc-alias

 

tsc-alias를 받아 다음과 같이 package.json에 설정을 추가하여 사용하면 컴파일 할 수 있다.

 

"scripts": {
    "build": "tsc && tsc-alias"
}

 

tsc-alias를 사용하면 타입스크립트의 `baseUrl`과 `paths` 설정을 사용하여 모듈 경로를 해석하고,

 

실제 파일 경로로 변환할 수 있다.  이를 통해서 모듈 경로를 상대 경로 대신 모듈 이름으로 작성할 수 있게된다.

 

즉, 올바르게 컴파일을 할 수 있도록 도와주는 역할을 한다.( 컴파일을 해주지는 않는다. )

 

 

baseUrlpaths의 예제를 한 번 보도록하자. 

 

"baseUrl": "./src",
"paths": {
    "@user/*": ["user/service/*"],
    "@board/*": ["board/*"],
    "@hooks/*": ["hooks/*"]
}

 

baseUrl은 현재 디렉토리(루트)에 있는 src 폴더를 기준으로 import의 디폴트를 설정한다.

 

디렉토리 구조

 

즉, import 문을 작성할 때 ./src 부터 작성했던 것을 user/, board/, hooks/ 등으로 바로 작성해도 된다.

 

// baseUrl을 설정하지 않았을 때
import foo from "./src/user/service/user.service"

// baseUrl을 설정했을 때
import foo from "user/service/user.service"

 

paths는 모듈을 할 때에 더 짧은 이름으로 import를 가능하게 한다.

 

// baseUrl을 설정하지 않았을 때
import foo from "./src/user/service/user.service"

// baseUrl의 설정은 했으나 paths를 설정하지 않았을 때
import foo from "user/service/user.service"

// paths을 설정했을 때
import foo from "@user/user.service"

 

타입스크립트를 사용할 때 편하게 사용할 수 있지만, 컴파일을 해주지는 않는다.

 

이를 컴파일하기 위해서는 별도의 추가 설정이 필요하다.

 

 

tsconfig-paths

 

위의 설정들은 컴파일러에 의해서만 적용되고 실제로 런타임 환경에서는 적용되지 않는다.

 

tsconfig-paths는 이 설정을 런타임 환경에서도 적용할 수 있도록 해준다.

 

require("tsconfig-paths/register");

 

위와 같이 모듈을 불러와서 실행을 하게되면, baseUrl과 paths 설정이 적용된다.

 

tsconfig-paths는 ts-node와 함께 사용할 수 있드며, ts-node의 --require 옵션을 사용하여

 

런타임 환경에서 tsconfig-paths/register 모듈을 자동으로 불러올 수 있다.

 

 


3. ts-node

 

 

타입스크립트로 코드를 작성해서, 실행을 해야하는데 이를 위해서는 항상 빌드하는 과정이 필요하다.

 

코드를 작성해서 확인하고 싶을 떄마다 빌드하는 과정을 반복하다보면 오랜시간이 걸리게 되는데

 

ts-node를 사용하면 이를 해소할 수 있다.

 

 

ts-node를 사용하면 실질적으로 빌드가 진행되고 있지만 눈에는 보이지않는다.

 

$ npm install -D ts-node
$ npm install -g ts-node

 

위와 같이 ts-node를 설치하고, ts-node를 사용하면 .ts 확장자를 가진 파일을 바로 사용할 수 있다.

 

ts-node도 여러가지 옵션 값들이 있고, 이를 통해서 타입스크립트 코드를 실행할 때 동작을 조정할 수 있다.

 

 

--compiler - 타입스크립트 컴파일러 설정 파일의 경로를 지정한다. 기본값은 tsconfig.json 이다.

 

--type-check - 타입 체크를 수행할지 여부를 지정한다. 기본값은 true 이다.

 

--transpile-only - 타입 체크를 수행하지 않고, TS를 JS로 변환하며, 실행 속도가 빨라진다. 기본값은 false이다.

 

--ignore - 실행시 제외할 타입스크립트 파일 패턴을 지정한다. 기본값은 node_modules이다.

 

--files - 실행할 TS 파일을 지정한다.

 

--skip-ignore - '.gitignore', '.ignore' 파일을 무시하고 모든 파일을 실행할지 여부를 지정한다. 기본값은 false이다.

 

 

ts-node tsconfig-paths는 함께 사용할 수 있다.

 

 

$ ts-node --require tsconfig-paths/register [파일명].ts

 

 

이를 package.json의 script에 설정하여 간단하게 사용할 수 있다.

'JavaScript > Typescript' 카테고리의 다른 글

전략패턴 실습코드(230420)  (0) 2023.04.23
타입스크립트 문법(2)  (0) 2023.04.20
타입스크립트 문법(1)  (0) 2023.04.19
타입스크립트 실습코드(OOP) (230419)  (0) 2023.04.19
타입스크립트(Typescript)란?  (0) 2023.04.18