https://typescript-kr.github.io/pages/module-resolution.html
위 내용을 보면 d.ts 파일을 찾는 방법이 있는데...이게 맞는지 모르겠다.
d.ts 에 들어가는 내용에 따라 인식하는 위치가 다른거 같다.
내가 배포한 모듈의 d.ts 파일 위치는 package.json의 typings 에 세팅하면 된다. 세팅을 안하면 d.ts의 내용을 인식하지 못한다.
그러면 모듈을 받아서 사용하는 사람들은 tsconfig에 typeRoots에 추가없이 사용이 가능하다.
이 때 d.ts에 들어가는 내용은 기본적으로 어느 사이트/블로그를 봐도 나와있는 내용들이다.
예를 들면
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //d.ts declare module utils { interface type { isObject(source: any) : boolean; isFunction(source: any) : boolean; isNumber(source: any) : boolean; isString(source: any) : boolean; isBoolean(source: any) : boolean; isDate(source: any) : boolean; isArray(source: any) : boolean; isError(source: any) : boolean; isUndefined(source: any) : boolean; isEmpty(source: any) : boolean; isNull(source: any) : boolean; isUndefinedOrNull(source: any) : boolean; isUndefinedOrEmpty(source: any) : boolean; isUndefinedOrNullOrEmpty(source: any) : boolean; } } export const gyType: utils.type; | cs |
이런 내용이다.
module이나 namespace를 선언하고, 필요한 선언을 한다.
그런데 나는 위의 일반적인 내용에 더불어 Array의 prototype에 함수를 추가하고 싶었다. Array의 prototype에 함수를 추가하려면 d.ts에 아래의 내용을 추가하고 ts파일에 구현을 하면 된다.
1 2 3 4 5 | declare global { interface Array<T> { deepCopy(): Array<T>; } } | cs |
d.ts에 위와 같이 global 내부에 interface 선언 병합을 이용해서 추가를 하고, ts 파일에 구현을 해주면 된다.(명시적 import일 경우에는 global이 필요없는 것으로 보인다.)
declare global 구문을 사용할 때는 하나 이상의 export나 import 구문이 필요하다. 없으면 에러남. export나 import 할 것이 없다면 export {}; 이것을 추가해주면 된다.
이 내용을 구현해서 github에 올린 후, 다른 프로젝트에서 불러와서 사용하려고 하면 Array의 deepCopy를 찾지 못한다.
이유는 모르겠는데, declare global로 구현한 추가 interface의 경우에는 typeRoot에 추가를 해줘야 인식하는거 같다.
그래서 결론적으로 d.ts파일을 소스의 ./@types/[modue_name]/index.d.ts에 넣어놨다.
그리고 package.json의 typings에는 "./@types/[module_name]/index.t.ds"로 하고, 이 모듈을 불러서 사용하는 프로젝트의 tsconfig typeRoot에 "node_modules/[module_name]/@types" 추가를 해줬다.
참고로 tsconfig의 typeRoot에 추가된 path에서 d.ts를 찾을 때, 모듈의 이름으로 된 폴더를 검색하고 그 폴더 안에서 index.d.ts파일을 찾는다. 그래서 모듈에서 d.ts파일을 만들 때 ./@types의 바로 아래에 index.d.ts를 만든게 아니고, module_name의 폴더를 만들고 그 안에 index.d.ts를 넣은 것이다.
댓글 없음:
댓글 쓰기