타입스크립트 설정파일 : tsconfig.json

2025. 6. 2. 13:37Coding Study/Typescript

 

설정 파일이 변경되었는데도 동작 하지 않는다면 typescript 서버를 재 실행 하면 된다.

 cmd + shift + p

 restart 검색 후 typescript 서버 재 실행

 

 

{
  "compilerOptions": { 
    "target": "ESNext",                // 자바스크립트 최신 버전 컴파일(ES5, ES6 , ES2016....)
    "module": "commonjs",                    // 모듈 시스템에 대한 컴파일
    "esModuleInterop": true, 
    "forceConsistentCasingInFileNames": true, // 대소문자 일관성 강제 여부
    "strict": true,                      // type 검사 엄격하게 (일반적으로 true 적용)
    "skipLibCheck": true,
    "outDir": "dist",                   // dist 폴더 내에 컴파일파일을 생성한다.
    "noUncheckedIndexedAccess": true,   // 타입검사를 좀더 엄격하게 한다.
    "lib" : ["ES6"],                   // Type 검사에 포함할 목록
    "skipLibCheck" : true             // 라이브러리의 타입정의파일의 타입검사 생략    
  },
  "includ":["src/**/*"]             // src 폴더내의 모든 파일 컴파일 한다.
  "ts-node":{
    "esm" : true
  }
}

 

target

 - ES5

 - ES6

 - ESNext ( 최신 버전 적용)

 

module

 - commonJS

 - ESNext ( 최신 버전 적용)

 

strict

 strict 를 true 로 적용 하게 되면 함수의 매개변수의 타입을 지정하지 않으면 오류가 발생한다.

 

moduleDetection : "force"

다른 파일이라도 TypeScript 는 전역변수로 취급을 해서 변수이름을 같은 이름을 쓰게 되면 오류가 발생 한다.

이때 moduleDetection 옵션을 force 로 작성하면 각각의 파일을 개별 모듈로 만들어 줘서 해결한다.

 

바로 바뀌지 않으면 아래와 같이 진행 해서 재실행 시킨다.

 

 

ts-node 

 타입스크립트를 실행하기 위해서는 컴파일된 js 파일을 터미널에서 node 명령어로 실행이 가능하다.

 매번 컴파일 후 실행하기는 번거롭기 때문에 타입스크립트를 컴파일 하지 않고 실행 하는 명령어가 ts-node 이다.

 하지만 ts-node 는 module 시스템을 해석하지 못하기 때문에 이 옵션을 작성해야 실행이 가능 해진다.

 

strictNullChecks

 상위 옵션 : stric ( stric 가 true 면 strictNullChecks를 따로 설정하지 않을 경우에는  true 이다.)

 타입스크립트에는 null 이라는 타입과 number 라는 타입이 따로 존재 하기때문에 number 로 지정된 변수에 null 을 넣게 되면

 허용이 되지 않는다.

 이때 strictNullChckes 를 false 로 하게 되면 숫자 타입에 null 값을 넣는것도 허용이 가능 하다.

 

 

"noImplicitAny" : fasle

 false 로 적용 시 암시적으로 추론 불가능한 타입을 any 타입으로 추론을 해서 타입 적용을 안해도 오류가 발생 하지 않는다.

 

 

"allowJs" : true

 true 로 적용 시 JavaScript 파일도 허용 한다

 

 

React_Vite 환경에서의 설정 내용

1. 파일별 역활

  1) tsconfig.app.json

       - 브라우저 환경에 맞춘 설정

 

 

   2) tsconfig.node.json

       - node.js 환경에 맞춘 설정

       - 빌드 나 테스트 스크립트가 node 환경에서 실행 될때

       - SSR(서버 사이트 렌더링)을 할때

       - Next.js 같은 프레임워크에서는 서버사이드 코드를 다루므로 필요하다.

 

 

2. 프로젝트 설정 내용

 tsconfig.app.json 파일 설정 내용 분석

{
  "compilerOptions": {
    "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
    "target": "ES2022",
    "useDefineForClassFields": true,
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "moduleDetection": "force",
    "noEmit": true,
    "jsx": "react-jsx",

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,               // 사용하지 않는 지역 변수 오류
    "noUnusedParameters": true,           // 사용하지 않는 매개변수 오류("_"로 시작하는 변수는 검사제외)
    "erasableSyntaxOnly": true,           
    "noFallthroughCasesInSwitch": true,   // switch 문에서 case에 break 또는 return 미포함 시 오류
    "noUncheckedSideEffectImports": true,
    "baseUrl": "src",
    "paths": {
      "@/*": ["*"]
    }
  },
  "include": ["src"]
}

 

 

 1) erasableSyntaxOnly

    - true : 타입 관련 구문만 제거 (구문만)

    - false :  타입 관련 구문 완전 제거

 

   ▶︎  예시: import type과 일반 import 차이

// types.ts
export type User = {
  id: number
  name: string
}
export const foo = 123

 

// main.ts
import type { User } from './types'
import { foo } from './types'

console.log(foo)

 

 

 컴파일 결과 

  < erasableSyntaxOnly : false >

import { foo } from './types'

console.log(foo)

 

    < erasableSyntaxOnly : true>

import type { User } from './types'
import { foo } from './types'

console.log(foo)

 

 

2. noUncheckedSideEffectImports

- 사이드 이펙트 없는 모듈에 대해 일반 import 대신 import type 권장 및 경고

 

// types.ts
export type User = {
  id: number
  name: string
}

 

 

// main.ts
import { User } from './types'  //noUncheckedSideEffectImports: true 일 경우 오류

 

 

아래와 같이 type 을 써서 import 해야 한다.

import type { User } from './types'  // 타입 전용 import