推荐答案
npm install @nuxtjs/sitemap
在 nuxt.config.js 中配置:
// www.javascriptcn.com code example
export default {
modules: [
'@nuxtjs/sitemap'
],
sitemap: {
hostname: 'https://example.com',
gzip: true,
routes: [
'/page1',
'/page2',
{
url: '/page3',
changefreq: 'daily',
priority: 0.8
}
]
}
}本题详细解读
1. 安装 @nuxtjs/sitemap 模块
首先,你需要通过 npm 或 yarn 安装 @nuxtjs/sitemap 模块:
npm install @nuxtjs/sitemap
或者使用 yarn:
yarn add @nuxtjs/sitemap
2. 配置 nuxt.config.js
安装完成后,你需要在 nuxt.config.js 文件中添加 @nuxtjs/sitemap 模块,并进行相应的配置。
// www.javascriptcn.com code example
export default {
modules: [
'@nuxtjs/sitemap'
],
sitemap: {
hostname: 'https://example.com', // 你的网站域名
gzip: true, // 是否生成 gzip 压缩的 sitemap 文件
routes: [
'/page1', // 静态路由
'/page2', // 静态路由
{
url: '/page3', // 动态路由
changefreq: 'daily', // 更新频率
priority: 0.8 // 优先级
}
]
}
}3. 配置选项详解
- hostname: 你的网站域名,必须包含协议(如
https://)。 - gzip: 是否生成 gzip 压缩的 sitemap 文件,默认为
false。 - routes: 定义需要包含在 sitemap 中的路由。可以是简单的字符串路径,也可以是包含更多配置的对象。
4. 动态路由
对于动态路由,你可以通过 routes 数组中的对象来配置。例如:
{
url: '/page3',
changefreq: 'daily',
priority: 0.8
}- url: 路由的 URL。
- changefreq: 页面的更新频率,可选值有
always,hourly,daily,weekly,monthly,yearly,never。 - priority: 页面的优先级,范围从
0.0到1.0。
5. 自动生成路由
如果你希望自动生成路由,可以使用 generate.routes 选项来动态生成路由列表。例如:
// www.javascriptcn.com code example
export default {
sitemap: {
hostname: 'https://example.com',
gzip: true,
routes: async () => {
const { data } = await axios.get('https://api.example.com/pages')
return data.map(page => `/pages/${page.slug}`)
}
}
}6. 生成 sitemap.xml
配置完成后,Nuxt.js 会在构建时自动生成 sitemap.xml 文件,并放置在 dist 目录下。你可以通过访问 https://example.com/sitemap.xml 来查看生成的 sitemap。
7. 高级配置
@nuxtjs/sitemap 模块还支持更多高级配置,如自定义 sitemap 文件名、多语言支持、排除特定路由等。你可以参考官方文档进行更深入的配置。