添加自定义代码

以 Markdown 格式查看

本页面介绍如何向您的 TypeScript SDK 添加自定义逻辑、方法和依赖项。

添加自定义逻辑

开始添加自定义代码:

1

创建新文件并添加您的自定义逻辑

src/helper.ts
1export function myHelper(): void {
2 return console.log("Hello world!");
3}
2

将您的文件添加到 .fernignore

.fernignore
1# 指定不应被 Fern 修改的文件
2
3src/helper.ts
3

使用 helper 函数

现在您的用户可以通过从 SDK 导入来使用 helper 函数。

1import { myHelper } from "sdk/helper";
2
3myHelper();

默认情况下,TypeScript 生成器只为您的 API 定义在 package.json 中自动生成 exports 条目。如果您希望消费者通过专用子路径导入您的自定义文件(例如 import { myHelper } from "@acme/sdk/helper"),您必须在 generators.yml 中使用 packageJson.exports 手动注册:

generators.yml
1- name: fernapi/fern-typescript-sdk
2 version: 3.69.0
3 config:
4 packageJson:
5 exports:
6 "./helper": # 消费者导入路径 — 不是源文件路径
7 types: "./dist/cjs/helper.d.ts"
8 import:
9 types: "./dist/esm/helper.d.mts"
10 default: "./dist/esm/helper.mjs"
11 require:
12 types: "./dist/cjs/helper.d.ts"
13 default: "./dist/cjs/helper.js"

导出键(例如,"./helper")确定您的用户将使用的导入路径,无需与源文件路径匹配。这些条目会合并到生成的 exports 中,因此它们在重新生成时会持久存在。由于 Node.js 强制执行 exports 映射,在您在此处添加自定义文件之前,无法通过子路径导入它们。

自定义 SDK 方法

Fern also allows you to add custom methods to the SDK itself (e.g. client.my_method() ) by inheriting the Fern generated client and then extending it.

查看 Flatfile 在其 TypeScript SDK 中使用此流程的示例

1

导入并扩展生成的客户端

首先,从 ../client 导入 Fern 生成的客户端并将其别名为 FernClient。 然后,扩展 FernClient 并添加您想要的任何方法。

src/wrapper/MyClient.ts
1import { MyClient as FernClient } from "../client"; // 为 Fern 生成的客户端设置别名
2
3export class MyClient extends FernClient { // 扩展 Fern 生成的客户端
4
5 public myHelper(): void {
6 console.log("Hello world!");
7 }
8
9}

查看 Flatfile 在其 FlatfileClient 中的示例

2

导出扩展的客户端

更新您的 index.ts 文件以导出扩展的客户端而不是生成的客户端。

src/index.ts
1export { MyClient } from "src/wrapper/MyClient"; // 而不是 "src/client"

查看 Flatfile 的示例 index.ts

3

更新 .fernignore

wrapper 目录和 index.ts 都添加到 .fernignore

.fernignore
1+ src/wrapper
2+ src/index.ts

查看 Flatfile 的示例 .fernignore

4

使用方法

Now your users can consume the helper function by importing it from the SDK.

1client.myHelper()

自定义依赖项

专业版和企业版功能

此功能仅适用于专业版和企业版计划。如需开始使用,请联系 support@buildwithfern.com

要添加您的自定义代码所需的包,请在您的 generators.yml 中使用 extraDependenciesextraDevDependencies 选项。

generators.yml
1- name: fernapi/fern-typescript-sdk
2 version: 3.69.0
3 config:
4 extraDependencies:
5 lodash-es: '1.0.0'
6 extraDevDependencies:
7 "@types/lodash-es": '1.0.0'