본문 바로가기
타입스크립트( TypeScript)

[타입스크립트] tsconfig.json "lib" 속성

by BillyCho 2022. 12. 4.

test.ts 파일이 있다

const button = document.querySelector('button')!;

button.addEventListener('click', () => {
  console.log('Button has been clicked.')
})

 

ts 파일은 왜 document 가 unknown 이라 인식하지 않으며 

button이 addEventListener를 가지고 있음을 알고있을까 ? 

 

그것은 tsconfig.json 파일 속성에서 default로 설정이 되어있기 떄문이다

 

{
  "compilerOptions": {
  }
}

파일안에 compilerOptions 말 그대로 컴파일 시 설정을 할 수 있는 옵션이 있다

 ts 가 dom을 인식할 수 있는 부분은 

{
  "compilerOptions": {
    // "lib": []
  }
}

lib 속성에 default 로 설정되어 있기 떄문이다

 

그러면 lib: [] 사용을 통해 아무것도 사용하지 않는다고 설정을 바꿔보자

 

{
  "compilerOptions": {
    "lib": []
  }
}

빈 배열을 넣어 아무것도 사용하지 않게 적용했다

 

Cannot find name 'document'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.ts(2584)

 

 

그러면 바로 document에 위의 에러가 발생한다

위의 에러가 말한데로 lib 속성에 "dom.ts" 가 들어가 있지 않다고 말해주고 있다

 

위에 에러를 없애기 위해서 lib 를 주석처리 default 속성을 적용하거나

    "lib": [
      "dom",
    ]

요래 적용할 수 있다