요즘 공부/새로 알게된 것들

tsconfig.json파일 설정 - 상대경로 임포트에서 절대경로 임포트하기

요즈음 2024. 2. 14. 19:03
320x100

tscofig.json

타입스크립트를 자바스크립트로 컴파일할때 어떻게 변환할 것인지 세부 설정을 지정해주는 파일이라고 생각하면 쉽다.

상대경로, 절대경로를 설정하는 옵션도 있어 유용하게 사용하기 편하다.

간단한 개념 및 옵션 요약이 있는 링크 :: https://codingapple.com/unit/typescript-tsconfig-json/



1. 기본 config파일

현재 하고 있는 프로젝트의 기본 config파일의 예시

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": [
    "src"
  ]
}

baseUrl

  • 절대경로를 기준으로 하는 기본 디렉터리를 지정하는 것
  • 지금 프로젝트에서는 src 폴더를 기준으로 작업을 하고 있기 때문에 src폴더를 기본 폴더로 설정한다.
    {
    "compilerOptions": {
      "target": "es5",
      "baseUrl" : "src", //이곳에서 추가하여 기본 디렉터리를 지정해준다
      "lib": [
        "dom",
        "dom.iterable",
        "esnext"
      ],
      "allowJs": true,
      ...
      ...
      ..}
    }

paths

  • 모듈 이름과, 해당 모듈 파일의 경로를 매핑하는 설정
    "paths":{
    "pages/*" : ["pages/*"],
    "components/*": ["components/*"]
    }




2. 세팅 적용 전후 차이

기존에는 상대경로로 (../../) 컴포넌트를 임포트했다면, 절대경로 루트로 컴포넌트를 탐색할 임포트해서 불러 올 수 있게 되었다.

옵션추가 config파일

{
  "compilerOptions": {
    "baseUrl": "src", //추가
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx"
  },
  "include": ["src"],
  "paths": { //추가
    "pages/*": ["pages/*"],
    "components/*": ["components/*"]
  }
}

import 경로 변화

import Header from '../../component/header'; -> import Header from 'component/header'
반응형