[TS] Typescript에서 JS 활용

He SEO·2022년 4월 8일

상황

Typescript로 작성하고 있는 프로젝트에 javascript 파일을 참조해야 하는 상황

해결

바로 사용할 수는 없고, d.ts 파일을 생성해야 하는데, 생성하는 방법은 2가지가 있음

방법 1) npm install로 자동 생성

@types를 붙이면 node_modules/@types에 d.ts 파일이 생성됨

//test는 filename
npm install @types/test 

typescript 파일에서 import 함

import * as test from 'test'

방법 2) 직접 d.ts 파일 생성

  • js 파일에 module.export 추가
  • d.ts 파일 생성
  • bin에 저장
  • typescript 파일에서 호출
//test.js
module.exports = {
  play: function() {
      return 'test result'
    }
}

d.ts 파일 수동 생성

//test.d.ts
import "./test.js"

declare function play(): string;

생성된 d.ts 파일을 bin에 저장

typescript 파일에서 import

import * as test from "./test";

function main(input: string) {
  return test.play();
}

참고 사이트

🔗 Angular 개발자의 개발 기록

profile
BACKEND 개발 기록 중. 감사합니다 😘

0개의 댓글