typescript 怎么编写公共工具库同时携带自己的声明文件?
使用 nestjs 写项目,因为需要将部分 公共工具类、常量 还有 TS 的接口等抽离出来
因此新建了一个工具库 主要结构如下
common-ts ├─ src │ ├─ constants │ │ ├─ Delimiter.ts │ │ ├─ Formation.ts │ │ └─ index.ts │ ├─ interface │ │ ├─ AppId.interface.ts │ │ ├─ index.ts │ │ ├─ TraceId.interface.ts │ │ └─ Validatable.interface.ts │ ├─ util │ │ ├─ EnvUtil.ts │ │ ├─ index.ts │ │ ├─ JwtUtil.ts │ │ ├─ RespUtil.ts │ │ └─ StrUtil.ts │ ├─ lib │ │ └─ IBC.d.ts │ └─ index.ts ├─ typings │ └─ index.d.ts ├─ gulpfile.ts ├─ package-lock.json ├─ package.json ├─ rollup.config.ts ├─ tsconfig.eslint.json ├─ tsconfig.json
现在遇到一个问题,我在 src/lib/IBC.d.ts
中手写了如下声明
declare namespace IBC { export interface Response { code: number; msg: string; timeStamp: string; data?: ResponseData; traceId?: string; } ...
}
然后工具类 src/util/RespUtil.ts
中如下代码
//RespUtil.ts
/** * 响应失败 * * @param code - 响应码 * @param msg - 响应消息 * @return IBC.Response * * @public */
export function fail(code: number, msg: string): IBC.Response { return { code: code, msg: msg, timeStamp: moment().format(), };
}
这个工具类中使用了 IBC.d.ts
其它工具类中都没有使用
现在在另一个项目中引入这个工具库,
结果没办法使用 IBC.d.ts 里面写好的描述
也没办法找到 RespUtil
而其它的公共类都可以正常使用。
tsconfig.json 如下
{ "compilerOptions": { "experimentalDecorators": true, /* 基础配置 */ "target": "esnext", "lib": [ "DOM", "ESNext" ], "removeComments": false, "declaration": true, "sourceMap": true, "allowJs": true, /* 强类型检查配置 */ "strict": true, //会防止你忘记在函数末尾返回值。 "noImplicitAny": false, //会防止在 switch 代码块里的两个 case 之间忘记添加 break 语句。 "noFallthroughCasesInSwitch": true, /* 模块分析配置 */ "baseUrl": ".", "outDir": "./dist", "esModuleInterop": true, "moduleResolution": "node", "resolveJsonModule": true, }, "include": ["src/**/*", "typings/**/*"], "exclude": ["node_modules", "build", "dist", "scripts", "webpack", "jest"]
}
typings/index.d.ts 如下:
declare module 'rollup-plugin-babel';
declare module 'rollup-plugin-eslint';
declare module 'conventional-changelog';