.js 파일에서 .d.ts 파일 만들기

.js 파일에서 .d.ts 파일 만들기

TypeScript 3.7부터 TypeScript는 JSDoc 문법을 이용해 JavaScript에서 .d.ts 파일을 생성하는 기능을 지원해요.

이 설정을 쓰면 프로젝트를 TypeScript로 이전(porting)하지 않고도, 코드베이스에서 .d.ts 파일을 직접 관리하지 않아도 TypeScript 기반 편집기의 편집 경험을 누릴 수 있어요. TypeScript는 대부분의 JSDoc 태그를 지원하며, 여기에서 그 참조를 확인할 수 있어요.

출처: TypeScript 핸드북

프로젝트가 .d.ts 파일을 생성하도록 설정하기

프로젝트에 .d.ts 파일 생성을 추가하려면 최대 네 단계가 필요해요.

  • 개발 의존성(dev dependencies)에 TypeScript 추가
  • TypeScript를 설정할 tsconfig.json 추가
  • TypeScript 컴파일러를 실행해 JS 파일에 대응하는 d.ts 파일 생성
  • (선택) package.json을 수정해 해당 타입을 참조

TypeScript 추가하기

이 부분은 설치 페이지에서 자세히 배울 수 있어요.

TSConfig

TSConfig는 컴파일러 플래그를 설정하고 파일을 어디서 찾을지 지정하는 jsonc 파일이에요. 이 경우에는 아래와 같은 파일이 필요합니다.

{
  // Change this to match your project
  "include": ["src/**/*"],

  "compilerOptions": {
    // Tells TypeScript to read JS files, as
    // normally they are ignored as source files
    "allowJs": true,
    // Generate d.ts files
    "declaration": true,
    // This compiler run should
    // only output d.ts files
    "emitDeclarationOnly": true,
    // Types should go into this directory.
    // Removing this would place the .d.ts files
    // next to the .js files
    "outDir": "dist",
    // go to js file when using IDE functions like
    // "Go to Definition" in VSCode
    "declarationMap": true
  }
}

옵션에 대해 더 알고 싶다면 tsconfig 참조를 확인하세요. TSConfig 파일을 쓰는 대신 CLI로 같은 동작을 할 수도 있어요.

npx -p typescript tsc src/**/*.js --declaration --allowJs --emitDeclarationOnly --outDir types

컴파일러 실행하기

이 부분은 설치 페이지에서 배울 수 있어요. 프로젝트의 .gitignore에 파일이 있다면, 그 파일들이 패키지에 포함되도록 잘 확인해 주세요.

package.json 수정하기

TypeScript는 package.json에서 모듈에 대한 노드 해석(node resolution)을 재현하되, .d.ts 파일을 찾는 추가 단계가 하나 더 있어요. 대략적인 해석 순서는 선택적인 types 필드를 먼저 확인하고, 그다음 "main" 필드, 마지막으로 루트의 index.d.ts를 시도하는 방식입니다.

Package.json Location of default .d.ts
No "types" field checks "main", then index.d.ts
"types": "main.d.ts" main.d.ts
"types": "./dist/main.js" ./dist/main.d.ts

없다면, "main"이 사용됩니다.

Package.json Location of default .d.ts
No "main" field index.d.ts
"main":"index.js" index.d.ts
"main":"./dist/index.js" ./dist/index.d.ts

.d.ts 파일에 대한 테스트를 작성하고 싶다면 tsdTSTyche를 시도해 보세요.

더 알아보기 (Learn more)