第一次编写Typescript软件包(NPM /私有软件包),但是对Typescript本身有丰富的经验。
说我的包裹叫做“ my-api”。它导出用于进行API调用的类以及这些API调用消耗/返回的模型。
models/
User.ts
index.ts
services/
BaseService.ts
UserService.ts
index.ts
index.ts
模型/User.ts
export type User = { ... }
models / index.ts
export { User } from "./User.ts";
services / BaseService.ts
export abstract class BaseService { ... }
服务/UserService.ts
export class UserService extends BaseService { ... }
服务/index.ts
export { UserService } from "./UserService.ts";
index.ts
export * from "./models";
export * from "./services";
我的声明最终看起来像这样(缩写):
declare module "models/User" {
export type User = { ... };
}
declare module "services/BaseService" {
export abstract class BaseService { ... }
}
declare module "services/UserService" {
import { BaseService } from "services/BaseService";
export class UserService extends BaseService { ... }
}
请注意,没有包围的my-api
模块等,这些声明位于根目录。
在通过NPM包含my-api
的应用中,我想使用以下类和类型:
CreateUserForm.ts
import { User, UserService } from "my-api";
// OR
import { User } from "my-api/models";
import { UserService } from "my-api/services";
export class CreateUserForm { ... }
在构建外部项目时,Typescript抱怨:
文件'/home/.../my-project/ui/node_modules/my-api/my-api.d.ts'不是模块。
我不知道如何说服Typescript创建适当的定义。
使用以下命令生成声明:
./node_modules/.bin/tsc --project ./tsconfig-definition.json --outFile ./dist/my-api.d.ts
tsconfig-definition.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"declaration": true,
"emitDeclarationOnly": true,
"noEmit": false,
"resolveJsonModule": false
},
"include": [ "./src" ]
}
tsconfig.json
{
"compilerOptions": {
"lib": ["dom", "es2015", "es2016"],
"jsx": "preserve",
"target": "es5",
"module": "esnext",
"moduleResolution": "node",
"declaration": false,
"noImplicitAny": false,
"noUnusedLocals": false,
"noUnusedParameters": false,
"removeComments": false,
"preserveConstEnums": true,
"sourceMap": true,
"skipLibCheck": true,
"allowJs": false,
"experimentalDecorators": true,
"esModuleInterop": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": false,
"strictNullChecks": false,
"noEmit": true,
"allowSyntheticDefaultImports": true,
"types": ["node"]
},
"include": ["src"]
}