2021년 2월 13일 토요일

[Typescript] github이나 npm에서 배포될 모듈을 만들 때 여러 개의 구분된 모듈을 하나로 만드는 방법

하나의 모듈에 type을 비교하는 기능과 로그를 쓰는 기능 두 개를 만든다고 가정하자.

프로젝트를 생성 후 src 폴더를 만든 후 rootDir(tsconfig.json)로 설정하고, outDir(tsconfig.json)을 "./"(root)로 설정한다.
    "outDir": "./",
    "rootDir": "./src",

src 아래에 lib 폴더를 만들고 type.ts, logger.ts 파일을 만든다.
그리고 root 아래에 @types 폴더를 만들고, 그 아래에 모듈 이름의 폴더를 만들고 그 폴더 안에 index.d.ts.파일을 만든다.(./@types/[module_name]/index.d.ts)
그리고 package.json에 typing 값은 위 index.d.ts의 위치를 입력해준다.(./@types/[module_name]/index.d.ts)

index.d.ts파일의 내용을 다음과 같이 한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
declare module gyUtils {
    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;
    }
 
    interface logger {
        info(data: any): void;
        error(data: any): void;
        warn(data: any): void;
        debug(data: any): void;
        trace(data: any): void;
    }
}
 
export const gyType: gyUtils.type;
export const gyLogger: gyUtils.logger;
cs

아래 export 된 두개의 변수를 이용하여 사용할 것이다

type.ts 파일에는 interface type 의 함수를 구현해준다.
1
2
3
4
5
6
7
export const isObject = (source: any): boolean => {
    return false;
}
 
export const isFunction = (source: any): boolean => {
    return false;
}
cs

함수 여러개를 구현해서 export 하면 된다.

logger도 같은 방식으로 구현한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
export const info = (data: any) => {
    const _a = {
        type: "info",
        datetime: new Date().format(),
        data
    }
    console.info(JSON.stringify(_a));
}
 
export const error = (data: any) => {
    const _a = {
        type: "error",
        datetime: new Date().format(),
        data
    }
    console.error(JSON.stringify(_a));
}
cs

그리고 root에 index.ts(package.json의 main)를 만들고 다음과 같이 한다.

1
2
3
4
5
const _type = require("./lib/type");
const _logger = require("./lib/logger");
 
export const gyType = _type;
export const gyLogger = _logger;
cs

다른 프로젝트에서 require()를 이용해 이 모듈을 불러오면 index.js(package.json의 main)을 호출하게 된다. index.js에서 export된 값이 gyType, gyLogger 두 개이며, 이 두개를 외부에서 사용하기 위해 d.ts에 동일하게 정의를 해준 것이다.

다른 프로젝트에서 다음과 같이 사용하면 된다.
1
2
const utils = require("gyutils");
console.log(utils.gyType.isArray([]));
cs

댓글 없음: