我有一个 Web API,我想为其构建一个库,这样我就不需要在与该 API 交互的每个新项目中编写相同的代码。
我还想拆分我的代码,因此每个端点结构都有一个类,因此,例如,假设我有多个用户端点,它们可以执行类似的操作
- 注册
- 登录
我会有一个提供这两种方法的 UserClient
export default class UserClient
{
register(email: string, password: string)
{
// code here
}
login(email: string, password: string, remember: bool)
{
// code here
}
}
所以,我的代码结构是这样的
package.json
tsconfig.json
--src
----api
------user-client.ts
----models
------user
--------logindata.ts
我的 tsconfig.json 看起来像这样
{
"compilerOptions": {
"declaration": true,
"declarationDir": "./dist",
"module": "commonjs",
"noImplicitAny": true,
"lib": ["es2017", "es7", "es6", "dom"],
"outDir": "./dist",
"target": "es2015",
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
},
"typedocOptions": {
"mode": "modules",
"out": "docs"
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"dist"
]
}
和我的 package.json
{
"name": "xxx",
"version": "1.0.0",
"description": "xxx",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"/dist"
],
"repository": "xxx",
"author": "xxx",
"license": "MIT",
"private": true,
"scripts": {
"build": "tsc",
"prepare": "npm run build",
"test": "echo \"Error: no test specified\" && exit 1"
}
}
所以我已经可以看到的是,我说我的 main 是 dist/index.js,类型是 dist/index.d.ts 并且我没有索引文件
所以我有多个问题
- 我需要在 src 中添加一个 index.ts 吗?如果是的话,里面会是什么?
- 我需要将类型更改为其他类型吗?
我基本上希望为我创建的每个类进行类型化,然后在另一个库中使用它,例如
import {UserClient} from "myLib"
import {BooksClient} from "myLib"
但是,当我现在使用 tsc 构建库时,它不会创建index.d.ts(因为我没有index.ts),而只是创建 user-client.js
和 user-client.d.ts
直接位于 dist 文件夹中(不尊重现有结构),我也不能在我的其他库中使用它们
最佳答案
好的,我修好了。首先,我们需要的是,客户端将被导出
所以user-client.ts
应该看起来像这样
export class UserClient
{
// code
}
然后,我在你的index.ts中遗漏了(或做错了),你需要导出而不是导入客户端
export {UserClient} from "./api/user-client"
然后,我使用 tsc
命令构建了我的文件,然后在我的消费库中,我能够使用 npm link ../jsapi
,然后只需使用
从“jsapi”导入 {UserClient}
没有任何问题。
我使用本教程作为帮助:https://www.tsmean.com/articles/how-to-write-a-typescript-library/但必须实际查看他们的 https://github.com/bersling/typescript-library-starter/blob/master/library-starter/src/index.ts得到正确答案
关于javascript - 使用类创建模块化 TypeScript 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62652197/