# @ascorbic/feed-loader 中文文档

规范地址：https://npmcn.com/package/%40ascorbic/feed-loader/

版本：2\.0\.1
npm 元数据更新时间：2025-06-26T08:10:37.792Z
中文译文更新时间：2026-11-06T22:36:03.876Z
软件包许可：MIT

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

原始 npm 页面：https://www.npmjs.com/package/%40ascorbic/feed-loader
原文对照：https://npmcn.com/package/%40ascorbic/feed-loader/?lang=original
项目主页：https://github.com/ascorbic/astro-loaders
源码仓库：https://github.com/ascorbic/astro-loaders

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

- 包体积（解压后）：40 kB，4 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：astro ^4\.14\.0 \|\| ^5\.0\.0
- 首次发布：2024-07-20T15:25:05.923Z
- 最新版本发布：2025-06-26T08:10:37.601Z
- 近 30 天下载量：2427（2026-10-07 至 2026-11-05，npm 官方下载统计）
- 已发布版本数：10（近 12 个月 0 个）

## 中文简介

此包为Astro提供饲料加载器. 它允许您加载和剖析 RSS, RDF, 和 Atom 种子, 并使用您的 Astro 站点中的数据 .

## 安装

```sh
npm install @ascorbic/feed-loader
```

也可以使用：`pnpm add @ascorbic/feed-loader`、`yarn add @ascorbic/feed-loader`、`bun add @ascorbic/feed-loader`

## README

# Astro 进取器

此包为Astro提供饲料加载器. 它允许您加载和剖析 RSS, RDF, 和 Atom 种子, 并使用您的 Astro 站点中的数据 .

货包包括两个装载器:

-   **`feedLoader`**: 用于构建时内容收藏的构建时种子加载
-   **`liveFeedLoader`**: 现场内容收集实验性运行时的饲料装载

## 安装

```sh
npm install @ascorbic/feed-loader
```

## 使用量

### 构建时种子加载( Static Collections)

您可以在内容配置中使用种子加载器 :

```typescript
// src/content/config.ts
import { defineCollection } from "astro:content";
import { feedLoader } from "@ascorbic/feed-loader";

const releases = defineCollection({
  loader: feedLoader({
    url: "https://github.com/withastro/astro/releases.atom",
  }),
});

const podcasts = defineCollection({
  loader: feedLoader({
    url: "https://feeds.99percentinvisible.org/99percentinvisible",
  }),
});

export const collections = { releases, podcasts };
```

然后,你可以像Astro的其他收藏一样使用这些:

```astro
---
import { getCollection } from "astro:content";
import Layout from "../layouts/Layout.astro";

const episodes = await getCollection("podcasts");
---

<Layout title="Episodes">
  <h2>Episodes</h2>
  <ul>
    {
      episodes.map((episode) => (
        <li>
          <a href={`/episodes/${episode.id.replace(/\W/g, "-")}`}>
            {episode.data.title}
          </a>
        </li>
      ))
    }
  </ul>
</Layout>
```

你可以使用 `render()` 函数 :

```astro
---
import { render, getEntry } from "astro:content";

const episode = getEntry("podcasts", Astro.params.id);

const { Content } = await render(episode);
---
<h1>{episode.data.title}</h1>

<Content />

<p>
    {
        episode.data.media.map((media) => (
            <audio controls>
                <source src={media.url} type={media.mimeType} />
            </audio>
        ))
    }
</p>

```

### 活饲料装入器( 实验)

> **实验特性**: 现场内容收藏需要 **Astro 5.1.0 或稍后时间** 而且是实验性的 API可能在未来的版本中有所改变.

实时 feed 加载允许您在请求时获取 RSS/Atom 种子而不是构建时间 。 对于您想要显示新数据而不重建您网站的经常更新的内容,此功能是有用的 .

#### 设置

1.  **启用现场内容收藏** 在你身边 `astro.config.mjs`数字 :

```javascript
export default defineConfig({
  // ...
  experimental: {
    liveContentCollections: true,
  },
});
```

2.  **创建活配置文件** 时间 `src/live.config.ts`数字 :

```typescript
// src/live.config.ts
import { defineLiveCollection } from "astro:content";
import { liveFeedLoader } from "@ascorbic/feed-loader";

const news = defineLiveCollection({
  type: "live",
  loader: liveFeedLoader({
    url: "https://feeds.bbci.co.uk/news/science_and_environment/rss.xml",
  }),
});

export const collections = { news };
```

3.  **在页面中使用活集**数字 :

```astro
---
// src/pages/news/index.astro
import { getLiveCollection } from 'astro:content';
import Layout from '../layouts/Layout.astro';

export const prerender = false; // Required for live content, unless using output: "server"

const { entries: articles, error } = await getLiveCollection('news', { limit: 10 });

if (error) {
  console.error('Failed to load news:', error.message);
}
---

<Layout title="Latest News">
  {error ? (
    <p>Error loading news: {error.message}</p>
  ) : (
    <ul>
      {articles?.map((article) => (
        <li>
          <a href={`/news/${encodeURIComponent(article.id)}`}>
            {article.data.title}
          </a>
          <p>{article.data.description}</p>
        </li>
      ))}
    </ul>
  )}
</Layout>
```

4.  **创建单个文章页面** 服务器侧渲染 :

```astro
---
// src/pages/news/[id].astro
import { getLiveEntry } from 'astro:content';
import Layout from '../../layouts/Layout.astro';

export const prerender = false; // Required for live content, unless using output: "server"

const { id } = Astro.params;
const { entry: article, error } = await getLiveEntry('news', decodeURIComponent(id!));

if (error || !article) {
  return Astro.redirect('/news');
}
---

<Layout title={article.data.title}>
  <h1>{article.data.title}</h1>
  <div set:html={article.data.description} />
  <a href={article.data.url} target="_blank">Read full article →</a>
</Layout>
```

#### 实况载入器选项

这个 `liveFeedLoader` 支持与 `feedLoader`数字 :

```typescript
liveFeedLoader({
  url: "https://example.com/feed.xml",
  requestOptions: {
    headers: {
      "User-Agent": "My Astro Site",
    },
  },
});
```

#### 过滤现场收藏

您可以在获取时过滤活集 :

```typescript
// Get latest 5 articles
const { entries } = await getLiveCollection("news", { limit: 5 });

// Filter by category
const { entries } = await getLiveCollection("news", { category: "science" });

// Filter by author
const { entries } = await getLiveCollection("news", { author: "john" });

// Filter by date range
const { entries } = await getLiveCollection("news", {
  since: new Date("2024-01-01"),
  until: new Date("2024-12-31"),
});
```

#### 处理错误

活性饲料加载器返回您可以适当处理的结构化错误 :

```typescript
import { FeedLoadError, FeedValidationError } from "@ascorbic/feed-loader";

const { entries, error } = await getLiveCollection("news");

if (error) {
  if (error instanceof FeedLoadError) {
    console.error(`Feed loading failed: ${error.message} (${error.code})`);
  } else if (error instanceof FeedValidationError) {
    console.error(`Feed validation failed: ${error.message}`);
  }
}
```

#### 何时使用 Live vs 静态加载

**使用实时加载 :**

-   内容经常更新(每天多次)
-   你需要实时数据
-   您想要避免重构内容更改
-   您正在构建预览功能

**使用静态加载时 :**

-   内容相对静止
-   业绩至关重要(在提交前)
-   您想要构建时间优化
-   您需要处理 MDX 或图像

## API 参考

### `feedLoader(options)`

静态内容集装器用于建设时的饲料处理.

### `liveFeedLoader(options)` ⚠️ **实验**

运行时回馈处理的活性内容收集加载器.

#### 选项

-   `url` (需要): 要获取的种子 URL
-   `requestOptions`: 自定义获取选项(标题等)

### 错误类型

-   `FeedError`: 基础错误类
-   `FeedLoadError`: 网络/ HTTP 错误
-   `FeedValidationError`: 种子解析/验证出错

## 常见问题

### @ascorbic/feed-loader 是什么？

此包为Astro提供饲料加载器\. 它允许您加载和剖析 RSS, RDF, 和 Atom 种子, 并使用您的 Astro 站点中的数据 \.

### 如何安装 @ascorbic/feed-loader？

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

### @ascorbic/feed-loader 支持 TypeScript 吗？

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

### @ascorbic/feed-loader 支持 ESM 还是 CommonJS？

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

### @ascorbic/feed-loader 可以商用吗？

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

### @ascorbic/feed-loader 的下载量有多少？

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

### @ascorbic/feed-loader 还在维护吗？

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

