Sitemap

自动为你的站点生成站点地图

配置参数

filename string

The sitemap file name

Default:
"/sitemap.xml"
query string

The query to search pages included in the sitemap

Default:
""
sort string

The values to sort the sitemap

Default:
"url=asc"
lastmod string function

The key to use for the lastmod field or a custom function

Default:
"date"
changefreq string function

The key to use for the changefreq field or a custom function

priority string function

The key to use for the priority field or a custom function

Description

此插件自动为你的所有页面生成 sitemap.xml 文件,这对于 SEO 很有用。 更多信息请查看 站点地图 XML 格式规范

它还会创建一个 robots.txt 文件,其中包含指向站点地图文件的链接,以便 搜索引擎更容易发现。

Installation

在你的 _config.ts 文件中导入此插件以使用它:

import lume from "lume/mod.ts";
import sitemap from "lume/plugins/sitemap.ts";

const site = lume();

site.use(sitemap(/* Options */)); // 选项

export default site;

Configuration

在内部,此插件使用 Search 来搜索并返回页面。默认情况下,所有页面都包含在站点地图中(除了 404 页面),并按 URL 排序。你可以设置不同的配置:

site.use(sitemap({
  filename: "my-sitemap.xml", // 用于更改站点地图文件名
  query: "", // 默认为空。你可以使用查询来过滤某些页面
  sort: "date=desc", // 按数据降序排序
}));

要使用查询过滤页面,请查看 search plugin 文档,这里有一些示例:

  • indexable=true 仅包含 indexable 值为 true 的页面。
  • !url^=/super-secret/ 包含所有页面,但不包括那些 URL 以 /super-secret/ 开头的页面
  • indexable=true !url^=/super-secret/ 两者的组合

Important

查询 url 搜索是区分大小写的,因此请务必确认你指定的任何 URL 的大小写。

要定义 URL,它使用在 配置文件 中定义的位置。

lastmod value

默认情况下,插件使用 date 变量的值作为 lastmod。这个 变量可以代表任何含义,但不一定是最后修改日期。如果你想使用页面文件的最后修改时间,你可以 创建一个如下的预处理器:

// 使用文件的 mtime 创建 lastmod 变量
site.preprocess([".html"], (pages) => {
  for (const page of pages) {
    const info = page.src.entry?.getInfo();
    page.data.lastmod = info?.mtime;
  }
});

// 配置插件以使用该变量
site.use(sitemap({
  lastmod: "lastmod",
}));

Note

mtime 不是一个可靠的值。在某些 CI 环境中,它是当前 时间(克隆仓库后文件被创建的时刻,而不是 此文件内容最后一次被修改的时间)。或者,你可以 使用 Git Last Updated 值:

import { getGitDate } from "lume/core/utils/date.ts";
site.preprocess([".html"], (pages) => {
  for (const page of pages) {
    const { entry } = page.src;
    page.data.lastmod = getGitDate("modified", entry.src);
  }
});

然而,这要求 CI/CD 环境执行深度克隆,而不是 仅获取最后一次提交的浅克隆。例如,Netlify 和 DigitalOcean 默认执行深度克隆,而 Vercel 和 Render 只能 执行浅克隆。Cloudflare Pages、GitHub Pages 和 GitLab Pages 默认执行浅克隆,但它们可以配置为执行 深度克隆。

Multilanguage

可以使用 multilanguage 插件为具有多种语言的站点生成站点地图:

import lume from "lume/mod.ts";
import multilanguage from "lume/plugins/multilanguage.ts";
import sitemap from "lume/plugins/sitemap.ts";

const site = lume();

site.use(multilanguage({
  languages: ["en", "gl", "es"],
}));
site.use(sitemap(/* Options */)); // 选项

export default site;