Skip to content

添加 RSS 源

Astro 支持博客和其他内容网站的快速、自动 RSS 提要生成。RSS 源为用户提供了一种订阅你的内容的简单方法。

¥Astro supports fast, automatic RSS feed generation for blogs and other content websites. RSS feeds provide an easy way for users to subscribe to your content.

¥Setting up @astrojs/rss

@astrojs/rss 提供了使用 API 端点 生成 RSS 提要的辅助程序。使用 固态继电器适配器 时,这可以解锁静态构建和按需生成。

¥The package @astrojs/rss provides helpers for generating RSS feeds using API endpoints. This unlocks both static builds and on-demand generation when using an SSR adapter.

  1. Install @astrojs/rss using your preferred package manager:

    Terminal window
    npm install @astrojs/rss
  2. Create a file in src/pages/ with a name of your choice and the extension .xml.js to be used as the output URL for your feed. Some common RSS feed URL names are feed.xml or rss.xml.

    The example file below src/pages/rss.xml.js will create an RSS feed at site/rss.xml.

  3. Import the rss() helper from the @astrojs/rss package into your .xml.js file and export a function that returns it using the following parameters:

    src/pages/rss.xml.js
    import rss from '@astrojs/rss';
    export function GET(context) {
    return rss({
    // `<title>` field in output xml
    title: 'Buzz’s Blog',
    // `<description>` field in output xml
    description: 'A humble Astronaut’s guide to the stars',
    // Pull in your project "site" from the endpoint context
    // https://astro.nodejs.cn/en/reference/api-reference/#contextsite
    site: context.site,
    // Array of `<item>`s in output xml
    // See "Generating items" section for examples using content collections and glob imports
    items: [],
    // (optional) inject custom xml
    customData: `<language>en-us</language>`,
    });
    }
See the @astrojs/rss README for the full configuration reference.

¥Generating items

items 字段接受 RSS 提要对象列表,可以使用 getCollection() 从内容集合条目生成,也可以使用 pagesGlobToRssItems() 从页面文件生成。

¥The items field accepts a list of RSS feed objects, which can be generated from content collections entries using getCollection() or from your page files using pagesGlobToRssItems().

RSS 源标准格式包括每个已发布项目的元数据,包括以下值:

¥The RSS feed standard format includes metadata for each published item, including values such as:

  • title:条目的标题。仅当设置了 description 时才是可选的。否则为必填项。

  • description:条目的简短摘录或描述。仅当设置了 title 时才是可选的。否则为必填项。

  • link:条目原始来源的 URL。(可选)

  • pubDate:条目的发布日期。(可选)

  • content:你帖子的完整内容。(可选)

See the items configuration reference for a complete list of options.

¥Using content collections

要创建 内容集合 中管理的页面的 RSS 源,请使用 getCollection() 函数检索 items 数组所需的数据。你需要从返回的数据中指定每个所需属性的值(例如 titledescription)。

¥To create an RSS feed of pages managed in content collections, use the getCollection() function to retrieve the data required for your items array. You will need to specify the values for each desired property (e.g. title, description) from the returned data.

src/pages/rss.xml.js
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
export async function GET(context) {
const blog = await getCollection('blog');
return rss({
title: 'Buzz’s Blog',
description: 'A humble Astronaut’s guide to the stars',
site: context.site,
items: blog.map((post) => ({
title: post.data.title,
pubDate: post.data.pubDate,
description: post.data.description,
// Compute RSS link from post `slug`
// This example assumes all posts are rendered as `/blog/[slug]` routes
link: `/blog/${post.slug}/`,
})),
});
}

可选的:替换现有的博客集合架构以强制执行预期的 RSS 属性。

¥Optional: replace your existing blog collection schema to enforce the expected RSS properties.

为了确保每个博客条目都生成有效的 RSS 提要项,你可以选择导入并应用 rssSchema,而不是定义架构的每个单独属性。

¥To ensure that every blog entry produces a valid RSS feed item, you can optionally import and apply rssSchema instead of defining each individual property of your schema.

src/content/config.ts
import { defineCollection } from 'astro:content';
import { rssSchema } from '@astrojs/rss';
const blog = defineCollection({
schema: rssSchema,
});
export const collections = { blog };

¥Using glob imports

Added in: @astrojs/rss@2.1.0

要从 src/pages/ 中的文档创建 RSS 源,请使用 pagesGlobToRssItems() 辅助程序。它接受 import.meta.glob 结果并输出有效 RSS 提要项目的数组(请参阅 有关编写通配符模式的更多信息 以指定要包含哪些页面)。

¥To create an RSS feed from documents in src/pages/, use the pagesGlobToRssItems() helper. This accepts an import.meta.glob result and outputs an array of valid RSS feed items (see more about writing glob patterns for specifying which pages to include).

src/pages/rss.xml.js
import rss, { pagesGlobToRssItems } from '@astrojs/rss';
export async function GET(context) {
return rss({
title: 'Buzz’s Blog',
description: 'A humble Astronaut’s guide to the stars',
site: context.site,
items: await pagesGlobToRssItems(
import.meta.glob('./blog/*.{md,mdx}'),
),
});
}

¥Including full post content

Added in: astro@1.6.14

content 键包含 HTML 格式的帖子的完整内容。这使你可以将整个帖子内容提供给 RSS 提要读者。

¥The content key contains the full content of the post as HTML. This allows you to make your entire post content available to RSS feed readers.

使用内容集合时,使用标准 Markdown 解析器(如 markdown-it)渲染帖子 body 并清理结果,包括渲染内容所需的任何额外标签(例如 <img>):

¥When using content collections, render the post body using a standard Markdown parser like markdown-it and sanitize the result, including any extra tags (e.g. <img>) needed to render your content:

src/pages/rss.xml.js
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
import sanitizeHtml from 'sanitize-html';
import MarkdownIt from 'markdown-it';
const parser = new MarkdownIt();
export async function GET(context) {
const blog = await getCollection('blog');
return rss({
title: 'Buzz’s Blog',
description: 'A humble Astronaut’s guide to the stars',
site: context.site,
items: blog.map((post) => ({
link: `/blog/${post.slug}/`,
// Note: this will not process components or JSX expressions in MDX files.
content: sanitizeHtml(parser.render(post.body), {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img'])
}),
...post.data,
})),
});
}

当将 glob 导入与 Markdown 结合使用时,你可以使用 compiledContent() 辅助程序来检索渲染的 HTML 以进行清理。注意:MDX 文件不支持此功能。

¥When using glob imports with Markdown, you may use the compiledContent() helper to retrieve the rendered HTML for sanitization. Note: this feature is not supported for MDX files.

src/pages/rss.xml.js
import rss from '@astrojs/rss';
import sanitizeHtml from 'sanitize-html';
export function GET(context) {
const postImportResult = import.meta.glob('../posts/**/*.md', { eager: true });
const posts = Object.values(postImportResult);
return rss({
title: 'Buzz’s Blog',
description: 'A humble Astronaut’s guide to the stars',
site: context.site,
items: posts.map((post) => ({
link: post.url,
content: sanitizeHtml(post.compiledContent()),
...post.frontmatter,
})),
});
}

¥Removing trailing slashes

Astro 的 RSS 提要默认生成带有尾部斜杠的链接,无论你为 trailingSlash 配置了什么值。这意味着你的 RSS 链接可能与你的帖子 URL 不完全匹配。

¥Astro’s RSS feed produces links with a trailing slash by default, no matter what value you have configured for trailingSlash. This means that your RSS links may not match your post URLs exactly.

如果你已在 astro.config.mjs 上设置 trailingSlash: "never",请在 rss() 助手中设置 trailingSlash: false,以便你的 feed 与你的项目配置相匹配。

¥If you have set trailingSlash: "never" on your astro.config.mjs, set trailingSlash: false in the rss() helper so that your feed matches your project configuration.

src/pages/rss.xml.js
import rss from '@astrojs/rss';
export function GET(context) {
const posts = Object.values(postImportResult);
return rss({
title: 'Buzz’s Blog',
description: 'A humble Astronaut’s guide to the stars',
site: context.site,
trailingSlash: false,
items: posts.map((post) => ({
link: post.url,
...post.frontmatter,
})),
});
}

¥Adding a stylesheet

设置 RSS 源的样式,以便在浏览器中查看文件时获得更愉快的用户体验。

¥Style your RSS feed for a more pleasant user experience when viewing the file in your browser.

使用 rss 函数的 stylesheet 选项指定样式表的绝对路径。

¥Use the rss function’s stylesheet option to specify an absolute path to your stylesheet.

rss({
// ex. use your stylesheet from "public/rss/styles.xsl"
stylesheet: '/rss/styles.xsl',
// ...
});

¥Enabling RSS feed auto-discovery

RSS 自动发现 允许浏览器和其他软件从主 URL 自动找到站点的 RSS 提要。

¥RSS autodiscovery allows browsers and other software to automatically find a site’s RSS feed from the main URL.

要启用,请将具有以下属性的 <link> 标记添加到你网站的 head 元素:

¥To enable, add a <link> tag with the following attributes to your site’s head element:

<link
rel="alternate"
type="application/rss+xml"
title="Your Site's Title"
href={new URL("rss.xml", Astro.site)}
/>

使用此标签,你的博客读者可以将你网站的基本 URL 输入他们的 RSS 阅读器中以订阅你的帖子,而无需 RSS 源的特定 URL。

¥With this tag, readers of your blog can enter your site’s base URL into their RSS reader to subscribe to your posts without needing the specific URL of your RSS feed.

¥Next Steps

your-domain.com/rss.xml 上的浏览器中访问你的 Feed 并确认你可以看到每个帖子的数据后,你现在可以 在你的网站上推广你的 Feed。将标准 RSS 图标添加到你的网站可以让你的读者知道他们可以在自己的提要阅读器中订阅你的帖子。

¥After visiting your feed in the browser at your-domain.com/rss.xml and confirming that you can see data for each of your posts, you can now promote your feed on your website. Adding the standard RSS icon to your site lets your readers know that they can subscribe to your posts in their own feed reader.

¥Resources

Astro 中文网 - 粤ICP备13048890号