# @contentful/experiences-client 中文文档

规范地址：https://npmcn.com/package/%40contentful/experiences-client/

版本：0\.10\.15
npm 元数据更新时间：2026-11-06T17:16:58.692Z
中文译文更新时间：2026-11-10T16:58:55.128Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40contentful/experiences-client
原文对照：https://npmcn.com/package/%40contentful/experiences-client/?lang=original
项目主页：https://github.com/contentful/experiences#readme
源码仓库：https://github.com/contentful/experiences

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：209 kB，10 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- 首次发布：2026-07-21T10:24:40.233Z
- 最新版本发布：2026-11-06T17:16:58.535Z
- 近 30 天下载量：5852（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：62（近 12 个月 62 个）

## 中文简介

交付客户端+获取体验

## 安装

```sh
npm install @contentful/experiences-client
```

也可以使用：`pnpm add @contentful/experiences-client`、`yarn add @contentful/experiences-client`、`bun add @contentful/experiences-client`

## README

# @ contentful/ 经验客户端

> **内部包裹.** 发布到npm,所以框架适配器可以在安装时解析,但是你并不打算直接导入. 它通过框架适配器进行过渡(`@contentful/experiences-react`, (中文(简体) ), `@contentful/experiences-svelte`(见a/c.5/49/70,附件).

隔离 `@contentful/experience-delivery` ——所生成的经验交付客户端——并拥有免费获取功能,有效载荷转换,交付出错,以及XDA衍生的请求类型. 共享运行时间和完成时间 `EventBuilder` 住在这里 `@contentful/experiences-runtime`,这取决于这个包。 客户端不构建事件或依赖运行时间. 现有的免费功能仍然支持适配器和应用集成.

* * *

## 这里面是什么

### `fetchExperience(experienceOptions, clientOptions, resolveOptions)`

主获取 + 解析出入口 。 获取经验有效载荷并将其解为 `PortableRenderPlan` 在一个电话。 有三种说法:

-   **按目的地路径** (推荐应用): `{ spaceId, destinationId, path }`。URL路径是目标路径.
-   **按目的地节点编号**数字 : `{ spaceId, destinationId, nodeId }`。 。 。 .
-   **根据经验d**数字 : `{ spaceId, environmentId, experienceId, … }`。当您已经持有身份标识时使用,并用于预览.

目的地表为空格( 无) `environmentId`, (中文(简体) ), `locale`, (中文(简体) ), `parameters` 或者说 `extensions`)并接受 `personalization`;随着它的设置,请求被作为 POST 发送,而不是缓存GET 。 他们回来了 `PortableRenderPlan | DestinationRedirectResult`: 重定向节点确定为 `{ redirect: { path } }`,你遵循而不是渲染.

```ts
const result = await fetchExperience(
  { spaceId, destinationId, path: '/demo/landing' },
  { accessToken: process.env.CDA_TOKEN! },
  { config: experienceConfig }
);
if ('redirect' in result) return redirect(result.redirect.path);
// result is a PortableRenderPlan
```

`preview: true` 目标抛出 `DestinationPreviewNotSupportedError` (一桥;用副编号表进行预览). 它不会开火 `{ client }` 树枝.

代号选项接受一等 `personalization` 对象中含有配置文件编号和事件。 其他经验交付选项仍在 `extensions`; 使用 `extensions: { sourceMap: {} }` 以请求内容源地图。 客户端同时合并到XDA请求正文中,并在存在任一能力时使用POST操作.

位码 `parameters` 接受字符串、数字和单级字符串/数字记录: `{ featuredPosts: { limit: 6, order: '-fields.title' } }`。在 `Experience.parameters` 参考文献 `$parameters/<id>`. 交付验证 名称、要求、倒数和值。 收藏单是签名的 `fields.<apiName>` 或者说 `sys.<id>` 路径,绝不 `OrderTerm[]`。 。 。 .

获取使用 `parameter.<id>` 财务报告和审定财务报表 `parameter.<id>.<field>` 在生成的客户端中 `queryParams`,从 `locale`选中空记录或定义的扩展名 POST , 有结构化、 无前缀 `parameters` 在体内。 dev.10支持这一点 机体通过序列器传递,尽管其生成的类型省去密钥; sDK使用本地打出的请求扩展名。 认证和重命名信头 仍然为生成的客户端所有。 使用已更改的值进行折射并替换 造物主的计划 [运行时间参数示例](https://npmcn.com/package/README.md#runtime-experience-parameters)。 。 。 .

三个定位参数组:

| 参数 | 类型 | 目的 |
| --- | --- | --- |
| `experienceOptions` | `{ spaceId, destinationId, path | nodeId, personalization? }` **或者说** `{ spaceId, environmentId, experienceId, locale?, parameters?, personalization?, extensions? }` | 要获取哪些经验:通过目的地或身份证明. |
| `clientOptions` | `{ accessToken, previewToken?, preview?, host? }` **或者说** `{ client }` | 如何取取——内置证书(带有可选预览取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取取. |
| `resolveOptions` | `{ config, metadata?, debug? }` | 如何解决——构成部分登记册,逐个提交 `metadata`,则a `debug` 开关. |

```ts
import { fetchExperience } from '@contentful/experiences-react'; // or experiences-svelte

// Inline credentials — client created internally
const plan = await fetchExperience(
  { spaceId: '...', environmentId: 'master', experienceId: slug, locale: 'en-US' },
  {
    accessToken: process.env.CDA_TOKEN!,
    previewToken: process.env.PREVIEW_TOKEN!, // optional — only required when preview: true
    preview: false, // flip to true for preview mode; picks previewToken + preview host
  },
  {
    config: experienceConfig,
    metadata: { slug }, // flows into resolveData hooks as ctx.experience.metadata
    debug: false, // logs + visible missing-component box when true
  }
);

// Pre-created client — useful when you manage the client lifecycle yourself
import { createClient } from '@contentful/experiences-react';
const client = createClient({ accessToken: process.env.CDA_TOKEN! });
const plan = await fetchExperience(
  { spaceId, environmentId, experienceId },
  { client },
  { config: experienceConfig }
);
```

回返 `PortableRenderPlan`。空节点有效载荷(草稿 / 未公布 / 空地 ) 解决一个有效的计划 `nodes: []` - 这不是404 对于缺少经验的案件,抓 `NotFoundError` (重新出口如下).

成功的对策可以带入上游的实地解析错误,同时有用 内容。 核心项目确认为可选错误 `plan.deliveryDiagnostics` 带有字符串的记录 `fieldPath` 财务报告和审定财务报表 `message`,维护秩序并省略 `originalError` 和未知的田园。 客户端保留有效载荷错误 by-ID GET/POST 和目的地转换;生成的-schema相容性保留 客户拥有,在Core有一个单一的正常化点.

目标出错可能具有更宽的形状, 因此此投影无法保证 完全覆盖。 缺失的字段不能证明个性化成功或 没有其他上游错误。 现有 `diagnostics: Error[]`,例外, 404处理,和剖面行为不变. 见 [分娩诊断 指导](https://npmcn.com/package/README.md#delivery-diagnostics) 安全展示和披露.

#### 预览模式

配置前翻两个符号 `preview: true` 每一次呼叫可以点击预览 API.

```ts
const experience = await fetchExperience(
  { spaceId, environmentId, experienceId },
  {
    accessToken: process.env.CDA_TOKEN!,
    previewToken: process.env.PREVIEW_TOKEN!,
    preview: previewMode, // boolean — flip per request
  },
  { config: experienceConfig }
);
```

-   `preview: false` (或未设定) − 用途 `accessToken` 对送货主.
-   `preview: true` • 用途 `previewToken` 相对于预览主机。 掷出 `fetchExperience() called with preview: true but no previewToken was provided` 若为 `previewToken` 缺少.
-   `host` 仅用于自定义基础 URL( stage, 代理, 每个区域)。 设定时,它战胜 `preview`\- 生成的主机 - 所以 `{ previewToken, preview: true, host: 'https://preview-staging…' }` 在您的自定义 URL 上使用预览符.
-   与 `{ client }` 选项, `preview` 被忽略( 创建自己的客户端, 带来自己的符号/ 主机选择 ) .

### `createClient(options)`

功能构造器结束 `ContentfulViewDeliveryClient` 匹配 SDK 选项形状 。 地图 `accessToken → token` 财务报告和审定财务报表 `host → baseUrl`;其他一切通过不变. 更喜欢 `new ContentfulViewDeliveryClient({...})` 因此字段名称与 `fetchExperience`'是内在证据路径.

`createClient` 是一个一次性的设置原始——它构建一个单一的客户端绑定在一个单一的符号上,而不参与每个请求 `preview` 切换。 如果需要在发送和预览之间进行运行时动态转换,请使用 `fetchExperience`'inline-creditics 路径 (`{ accessToken, previewToken, preview }`)而不是通过 `createClient` 并经过 `{ client }`。 。 。 .

```ts
import { createClient, PREVIEW_HOST } from '@contentful/experiences-react';

// Delivery (default)
const client = createClient({ accessToken: process.env.CDA_TOKEN! });

// Preview — use PREVIEW_HOST + a CPA token
const previewClient = createClient({
  accessToken: process.env.PREVIEW_TOKEN!,
  host: PREVIEW_HOST,
});

// Custom base URL (staging, proxy, per-region)
const customClient = createClient({
  accessToken: process.env.CDA_TOKEN!,
  host: 'https://preview-staging.example.com',
  // headers, timeoutInSeconds, maxRetries, fetch, logging pass through
});
```

#### `DELIVERY_HOST` 编号 : `PREVIEW_HOST` 编号 : `PREVIEW_WEBSOCKET_HOST`

为 Canonial 发送、预览和预览会话WebSocket URL 命名常数 。 使用它们就可以不用在应用程序中硬化URL字符串.

```ts
import { DELIVERY_HOST, PREVIEW_HOST, PREVIEW_WEBSOCKET_HOST } from '@contentful/experiences-react';

DELIVERY_HOST; // 'https://xdn.contentful.com'
PREVIEW_HOST; // 'https://preview.xdn.contentful.com'
PREVIEW_WEBSOCKET_HOST; // 'wss://preview.xdn.contentful.com'
```

`createClient` 是固定模式路径——一个客户端,一个符号,一个主机. 如果您需要在发送和预览之间翻转到每个请求(例如: `isPreview` URL 参数),使用 `fetchExperience`内在证书格式 `preview: boolean` 而不是在这里预建客户端。 见 [“审查模式”](https://npmcn.com/package/%40contentful/experiences-client/#readme-preview-mode) 见上文.

### `fetchDestinationSitemap(destinationOptions, clientOptions, paginationOptions?)`

为静态生成列出已公布的目标中的每个可移动路径, `sitemap.xml`或者其他散装行走 它不水合物 经验; 给每个 `path` 改为 `fetchExperience`。 。 。 .

```ts
import { fetchDestinationSitemap } from '@contentful/experiences-react';

const paths: string[] = [];
let pageNext: string | undefined;
do {
  const sitemap = await fetchDestinationSitemap(
    { spaceId, destinationId },
    { accessToken: process.env.CDA_TOKEN! },
    { pageNext } // limit defaults to 100, max 1000
  );
  paths.push(...sitemap.items.map((item) => item.path));
  pageNext = sitemap.pages.next;
} while (pageNext);
```

每个项目都是 `{ path, experienceId, type }`. 光标(`pages.next`, (中文(简体) ), `pages.prev`)是不透明的;不要结合 `pageNext` 财务报告和审定财务报表 `pagePrev`目标投出 `NotFoundError`。它只是自由函数;节点和Web运行时间没有站点映射方法.

### `NotFoundError`

从 `@contentful/experience-delivery` 作为值+类型。 由基本交付客户端投放404个响应. 引导它到您的框架的 404 平庸:

```ts
import { fetchExperience, NotFoundError } from '@contentful/experiences-react';

try {
  const experience = await fetchExperience(/* … */);
  // …
} catch (err) {
  if (err instanceof NotFoundError) notFound(); // Next.js
  throw err;
}
```

完整的交付客户错误命名空间也被再导出为 `ContentfulViewDelivery` (单位:千美元)`UnauthorizedError`, (中文(简体) ), `ForbiddenError`, (中文(简体) ), `ConflictError`, (中文(简体) ), `UnprocessableEntityError`, (中文(简体) ), `InternalServerError`, (中文(简体) ), `ContentfulViewDeliveryError`, (中文(简体) ), `ContentfulViewDeliveryTimeoutError`) (中文(简体) ).

### `ContentfulViewDeliveryClient`

直接从 `@contentful/experience-delivery`. 被曝光用于高级使用的情况下,您需要完全控制客户端(海关基础 URL,请求选项,跨调用重复使用). 大多数消费者应该更喜欢 `createClient` (上经.

```ts
import { ContentfulViewDeliveryClient } from '@contentful/experiences-react';

const client = new ContentfulViewDeliveryClient({
  token: process.env.CDA_TOKEN!,
  baseUrl: 'https://xdn.contentful.com', // default delivery endpoint
});
```

* * *

## 为什么是单独的包裹?

`@contentful/experiences-sdk-core` ——它必须保持可导入性,而不必拉入任何网络或平台代码。 经验传送客户端是大型的(~3000生成的文件),只有在进行服务器侧取时才需要. 在这里隔离意味着:

-   核心在任何环境中都保持精干和可使用(对接、安全部门改革、试验装置).
-   未来适配器从本地固定装置或自定义取取道中制取,不会支付送货客户端的重量.
-   交付客户端版本可以被撞到一个地方.

* * *

## 一揽子公约

-   不导入 `@contentful/experience-delivery` 除了这个包裹,从任何地方.
-   仅再向用户输出框架适配器需要的表面.
-   保留 `fetchExperience` 薄-取出+铸出+分辨率. 商业逻辑属于 `packages/core`。 。 。 .
-   SDK 选项和交付客户端选项之间的名称映射 `create-delivery-client.ts` - 一个地方需要改变.

## 许可证

麻省理工学院. 见寄存器 [`LICENSE`](https://npmcn.com/package/LICENSE) 财务报告和审定财务报表 [`NOTICE`](https://npmcn.com/package/NOTICE) 完全归属.

## 常见问题

### @contentful/experiences-client 是什么？

交付客户端\+获取体验

### 如何安装 @contentful/experiences-client？

在项目目录运行 npm install @contentful/experiences-client，或使用 pnpm add / yarn add / bun add。

### @contentful/experiences-client 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @contentful/experiences-client 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @contentful/experiences-client 可以商用吗？

@contentful/experiences-client 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @contentful/experiences-client 的下载量有多少？

根据 npm 官方下载统计，@contentful/experiences-client 在 2026/10/11 – 2026/11/09 这 30 天内被下载 5,852 次，日均约 195 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @contentful/experiences-client 还在维护吗？

最新版本 0\.10\.15 发布于 2026/11/07（4 天前）；至今共发布 62 个版本，其中过去 12 个月发布了 62 个；首次发布于 2026/07/21。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

