官方插件
在 GitHub 上查看插件gatsby-plugin-feed
为你的 Gatsby 网站创建一个 RSS feed(或多个 feed)。请注意:此插件仅在 production 模式下运行时生成 xml 文件!要测试你的 feed,请运行:gatsby build && gatsby serve。
安装
npm install gatsby-plugin-feed用法
gatsby-plugin-feed 使用 rss 包来生成 RSS feed。我们建议使用 gatsby-config 中的 siteMetadata 信息来定义 RSS feed 的 title、description 和 site_url。这些键会直接传递给 rss feedOptions。
gatsby-config.js
module.exports = {
siteMetadata: {
title: `Your site title`,
description: `Your site desccription`,
site_url: `https://your-site-url.com`,
}
}之后,你应该像这样在你的 gatsby-config 中配置 gatsby-plugin-feed(本例假设站点使用 Markdown 页面)
gatsby-config.js
module.exports = {
siteMetadata: {
title: `Your site title`,
description: `Your site desccription`,
site_url: `https://your-site-url.com`,
},
plugins: [
{
resolve: `gatsby-plugin-feed`,
options: {
feeds: [
{
serialize: ({ query: { site, allMarkdownRemark } }) => {
return allMarkdownRemark.nodes.map(node => {
return Object.assign({}, node.frontmatter, {
description: node.excerpt,
date: node.frontmatter.date,
url: site.siteMetadata.siteUrl + node.fields.slug,
guid: site.siteMetadata.siteUrl + node.fields.slug,
custom_elements: [{ "content:encoded": node.html }],
})
})
},
query: `
{
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] },
) {
nodes {
excerpt
html
fields {
slug
}
frontmatter {
title
date
}
}
}
}
`,
output: "/rss.xml",
title: "Your Site's RSS Feed",
},
],
},
},
],
}gatsby-plugin-feed 接受两个顶级插件选项
query(optional): 一个 GraphQL 查询,用于获取title、description和site_url。默认情况下,该插件查询siteMetadata。feeds(required): 你想定义的一个或多个 RSS feed。
feeds 本身具有这些必需的键
title: RSS feed 的标题output:xml文件的输出位置serialize: 你可以访问顶级query键以及feeds.query中的 GraphQL 查询。你必须返回一个包含 rssitemOptions键的对象数组query: 用于获取 RSS 条目内容的 GraphQL 查询
需要更多帮助? 查看文档 添加 RSS Feed。
附加选项
如上所述,gatsby-plugin-feed 接受可选的附加项。
feeds 具有这些附加选项
match: 配置,指示哪些页面将包含 feed 引用。match的可接受类型是string或undefined。默认情况下,当match未配置时,所有页面都将插入 feed 引用。如果提供了string,它将用于构建一个 RegExp,然后用于测试当前页面的pathname是否满足此正则表达式。只有满足此规则的页面才会包含 feed 引用。link: 此配置将覆盖从output生成的默认 RSS 链接。
所有附加选项都将传递给 rss 包的 feedOptions 部分。因此,你可以编写如下内容
gatsby-config.js
module.exports = {
siteMetadata: {/* siteMetadata contents */},
plugins: [
{
resolve: `gatsby-plugin-feed`,
options: {
feeds: [
{
serialize: ({ query: { site, allMarkdownRemark } }) => {
/* contents go here */
},
query: `/* query goes here */`,
output: "/rss.xml",
title: "Your Site's RSS Feed",
// Optional configuration specific for plugin:
match: "^/blog/",
link: "https://feeds.feedburner.com/gatsby/blog",
// Optional configuration passed through to itemOptions
custom_namespaces: {
media: 'http://search.yahoo.com/mrss/',
},
language: `en-US`,
},
],
},
},
],
}serialize 函数可以返回 rss itemOptions 设置的所有键。