# @contentful/experiences-svelte 中文文档

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

版本：0\.13\.9
npm 元数据更新时间：2026-11-06T17:15:12.597Z
中文译文更新时间：2026-11-10T17:28:10.820Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：221 kB，132 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：5 个
- peer 依赖：svelte ^5\.55\.7
- 首次发布：2026-07-21T10:25:54.642Z
- 最新版本发布：2026-11-06T17:15:12.341Z
- 近 30 天下载量：4247（2026-10-11 至 2026-11-09，npm 官方下载统计）
- 已发布版本数：68（近 12 个月 68 个）

## 中文简介

内容体验的Svelte适配器——服务器和客户端渲染器,通过可移植渲染器计划

## 安装

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

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

## README

# @ contentful/ 经验- svelte

> ⚠️ **阿尔法.** 发布至npm. API是不稳定的,并将改变.

内容体验SDK的斯维尔特适配器. 你带来了自己的Svelte 5组件;它使经验载荷从经验交付API(XDA)中与之并用.

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

这是你唯一安装的渲染SDK包. 它可以再出口你需要的一切 `@contentful/experiences-sdk-core`, (中文(简体) ), `@contentful/experiences-design`,以及 `@contentful/experiences-client`选项 `@contentful/experiences-live-preview` 软件包也是客户界面,并提供框架中性活预览客户端.

公共API镜像 `@contentful/experiences-react` 1:1为外形;只有渲染出原始物改变(Svelte 5) `Component`s, 片断代替 `children: ReactNode`,以及 `getDesignValues()` 改为 `useDesignValues()`) (中文(简体) ).

* * *

## 公共 API

### 撰写

```ts
defineComponent<Props>(config); // Type-narrowing identity for component-type configs
defineExperienceTemplate<Props>(config); // Same shape, for coded Experience Template configs
```

### 获取

```ts
fetchExperience(experienceOptions, clientOptions, resolveOptions); // Async; fetches by Destination path/node id or Experience id and resolves in one call
fetchDestinationSitemap(destinationOptions, clientOptions, paginationOptions?); // Async; lists every routable path in a Destination
fetchPreviewSession(previewSessionOptions, clientOptions, resolveOptions); // Async; fetches and resolves a Preview Session Experience
```

从目标服务页面: URL 路径是目标路径 。 重定向节点作为值而不是错误返回. 在目标上不支持预览( 它抛出) `DestinationPreviewNotSupportedError`; 预览时使用代号表.

```ts
const result = await fetchExperience(
  { spaceId, destinationId, path: '/demo/landing' },
  { accessToken },
  { config: experienceConfig }
);
if ('redirect' in result) {
  // follow it: navigate to result.redirect.path
}
// otherwise `result` is a PortableRenderPlan

// Enumerate every routable path, for example to prerender
const sitemap = await fetchDestinationSitemap({ spaceId, destinationId }, { accessToken });
const paths = sitemap.items.map((item) => item.path); // follow sitemap.pages.next for more
```

使用 `fetchPreviewSession` 内容应用程序时的初始渲染 页:1 `preview_session_id`预览会话 {\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}快照并解析成 `PortableRenderPlan`启用 `useLivePreview` 改为 接收随后的 WebSocket 更新 :

```ts
const plan = await fetchPreviewSession(
  { spaceId, environmentId, sessionId },
  { previewToken },
  { config: experienceConfig }
);
```

如果预览会话引用了来自其他空格的资源,则通过同样的 编码 `resourceResolution` 数值 `previewSessionOptions` 转至 `fetchPreviewSession` 财务报告和审定财务报表 `useLivePreview`。 。 。 .

### 解析器

```ts
resolveExperience(payload, config, opts?); // Async; walks payload, runs resolveData, returns a PortableRenderPlan
```

### 现场预览

使用 `useLivePreview` 当应用程序订阅预览会话更新时, 解决每个有效载荷,并将由此产生的计划从 `data`数字 :

```svelte
<script lang="ts">
  const livePreview = useLivePreview(() => ({
    previewSessionOptions,
    initialPayload,
    initialPlan,
    resolveOptions: { config: experienceConfig },
  }));
</script>

<ClientExperienceRenderer experience={livePreview.data} config={experienceConfig} />
```

单独获取原始有效载荷和制作计划,使用 `useLivePreviewExperience` 财务报告和审定财务报表 `useExperiencePlan`数字 :

```svelte
<script lang="ts">
  const livePreview = useLivePreviewExperience(() => ({
    previewSessionOptions: {
      spaceId,
      environmentId,
      previewToken,
      sessionId,
    },
    initialPayload,
  }));

  const plan = useExperiencePlan(() => ({
    payload: livePreview.data,
    initialPlan,
    resolveOptions: { config: experienceConfig },
  }));
</script>

<ClientExperienceRenderer experience={plan.data} config={experienceConfig} />
```

`useLivePreviewExperience` 返回最新的原始有效载荷. `initialPayload` 种子第一个值. `useExperiencePlan` 转换有效载荷 输入 `PortableRenderPlan` 由制造器所消耗并保持电流 正在解决最新情况.

现场审查的结果也暴露了 `error` 预览会话连接时 失败。 最后一个有效 `data` 现保留.

### 渲染器

```ts
ServerExperienceRenderer; // SSR-safe renderer
ClientExperienceRenderer; // Client renderer
MissingComponent; // Default fallback for unregistered component types
NodesRenderer; // Exposed so you can re-render a slot's raw nodes yourself (see Slot children)
```

### Styling + 运行时上下文 (帮助)

```ts
getDesignValues<T>(); // Escape hatch: the same resolved design record that auto-fills props; read in a $derived to stay reactive
toCss(design, options?); // Turns a design record into a plain style object, keeping only real CSS keys
getExperience(); // RenderContext: debug, metadata
getContentfulComponent(); // Raw payload for the enclosing node (or undefined), including `attribution`
getContentfulExperienceTemplate(); // Same, for an enclosing coded Experience Template node
getTrackingAttributes(attribution); // Attributes to spread on a node's outermost element for interaction tracking
type ToCssOptions;
```

确定的设计值为 **自动填入您的组件道具** 和内容一起。 样式从 `$props()` 是一条推荐路径. `getDesignValues()` 揭露出与出逃舱门相同的记录. 仅针对并非登记成分的被窝儿童,或用于在渲染道外所需的设计(一种效应,一种必须测量)——见 [样式组件](https://npmcn.com/package/README.md#styling-components)选项 `resolveToken` 在你身边 `Config` (单位:千美元)`type ResolveToken`) (中文(简体) ).

### 再出口类型和公用事业

```ts
// From core
type Config, Components, ExperienceTemplates, Registration, ExperienceTemplateRegistration,
type ComponentConfig, ExperienceTemplateConfig,
type ContentfulComponent, ContentfulExperienceTemplate,
type RenderContext, ResolveToken,
type ExperiencePayload, ExperienceNode, ComponentNode, ExperienceTemplateNode,
type PortableRenderPlan, PortableRenderNode, PortableRegistration,
type DesignPropValue, ManualDesignValue, DesignToken, ExperienceContext, ResolveContext,
type ResolverConfig, ResolveExperienceOptions

// From design
isCssProperty, toCssKey, CSS_PROPERTIES

// From client
fetchExperience, fetchDestinationSitemap, fetchPreviewSession, createClient, ContentfulViewDelivery,
ContentfulViewDeliveryClient, NotFoundError, DestinationPreviewNotSupportedError, PreviewSessionFetchError,
LivePreviewConnectionError,
DELIVERY_HOST, PREVIEW_HOST, PREVIEW_WEBSOCKET_HOST

type ExperienceOptions, ByIdExperienceOptions, ByDestinationPathExperienceOptions,
  ByDestinationNodeIdExperienceOptions, DestinationRedirectResult, DestinationSitemapResult,
  FetchDestinationSitemapOptions, FetchDestinationSitemapPaginationOptions, SitemapPathItem,
  PreviewSessionExperienceOptions, PreviewSessionClientOptions,
  PreviewSessionResolveOptions, ClientOptions, ResolveOptions, CreateClientOptions
```

* * *

## 快速引用

```svelte
<!-- Button.svelte: content + resolved design both arrive as props -->
<script lang="ts">
  interface ButtonProps {
    label?: string;
    url?: string;
    backgroundColor?: string; // resolved design, auto-filled
    color?: string;
  }

  let { label = 'Button', url, backgroundColor, color }: ButtonProps = $props();
</script>
{#if url}
  <a href={url} style="background: {backgroundColor}; color: {color};">{label}</a>
{:else}
  <button type="button" style="background: {backgroundColor}; color: {color};">{label}</button>
{/if}
```

```ts
// experience-config.ts
import {
  defineComponent,
  type Components,
  type Config,
  type ResolveToken,
} from '@contentful/experiences-svelte';
import Button from './components/Button.svelte';
import type { ButtonProps } from './components/Button.svelte';

const components: Components = {
  // Bare component, or defineComponent({...}) when you need defaults/resolveData.
  Button: defineComponent<ButtonProps>({
    resolveData: ({ content }) => ({ url: ensureScheme(content.url) }),
    component: Button,
  }),
};

const resolveToken: ResolveToken = (token) => designTokens[token.value];

export const experienceConfig: Config = { components, resolveToken };
```

```svelte
<!-- +page.svelte -->
<script lang="ts">
  import { ServerExperienceRenderer } from '@contentful/experiences-svelte';
  let { data } = $props();
</script>
<ServerExperienceRenderer experience={data.experience} config={experienceConfig} />
```

### 间隔儿童

每个插槽都是以插槽命名的道具 **片段数组** (单位:千美元)`Snippet[]`),每个孩子一个——不是一个包片. 对于普通的"让它们变成"例,用 `{#each}` 财务报告和审定财务报表 `{@render}`(笑声) (掌声) (掌声) (掌声) (掌声) (掌声) (掌声) (掌声) (掌声) (掌声) .

```svelte
<!-- Section.svelte -->
<script lang="ts">
  import type { Snippet } from 'svelte';

  let { children }: { children?: Snippet[] } = $props();
</script>

<!-- Common case — render them all: -->
<div>
  {#each children ?? [] as child}
    {@render child()}
  {/each}
</div>

<!-- Or take control of each child: -->
<!--
<div>
  {#each children ?? [] as child, i}
    <div class="cell">{@render child()}</div>
  {/each}
</div>
-->
```

`children` 不是特别的——它只是默认槽的常规名称. **每个** 有效载荷中的槽变成同名的 `Snippet[]` 道具,所以一个组件有一个 `header` 位置刚刚宣布 `header?: Snippet[]` 并让它同样的方式。 这同样适用于编码的经验模板:带有 `content` 槽收到一个 `content` 道具 (英语).

如果你宁愿自己制造一个插口的生节点,它们仍然在有效载荷上 `getContentfulComponent().slots` 联合国 `Record<string, PortableRenderNode[]>`)——交给 `NodesRenderer`。 。 。 .

关于全面开始的走过、合并优先规则和设计原理,见 [根读取](https://npmcn.com/package/README.md) 财务报告和审定财务报表 [`AGENTS.md`](https://npmcn.com/package/AGENTS.md)。 。 。 .

* * *

## 许可证

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

## 运行时间参数

位码 `fetchExperience` 接受 `parameters`,例如 `{ featuredPosts: { limit: 6, order: '-fields.title' } }`斯卡拉尔是弦或 数字; 记录叶有一个关卡。 命令是签字的 `fields.<apiName>` 或者说 `sys.<id>` 路径。 以已改变的值进行回溯,然后替换出质器的计划. 出口包括 `ExperienceParameters`, (中文(简体) ), `ExperienceParameterValue`, (中文(简体) ), `ExperienceParameterRecord`,以及 `ExperienceParameterOrder`。 。 。 . 见 [收藏/比较示例](https://npmcn.com/package/README.md#runtime-experience-parameters)。 。 。 .

## 常见问题

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

内容体验的Svelte适配器——服务器和客户端渲染器,通过可移植渲染器计划

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

在项目目录运行 npm install @contentful/experiences-svelte，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：svelte（^5\.55\.7）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

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

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

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

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

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

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

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

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

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

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

