BOYYANG/1/blog/卡通蓝发女孩 可爱动漫少女 4k壁纸 3840x2160_彼岸图网

nuxt3自定义生成sitemap文件

作者: boyyang
分类: 前端开发
发布: 2024-04-02 02:34:05
更新: 2025-03-23 11:43:24
浏览: 945

       在nuxt3中可以通过@nuxtjs/sitemap 生成sitemap.xml文件,官方链接 nuxtseo 。可以通过该库自动生成sitemap文件,并且可以自定义。

  • 安装库
bun install @nuxtjs/sitemap
  • 将包添加进nuxt.config.ts中的modules中
// https://nuxt.com/docs/api/configuration/nuxt-config
import {sitemap} from './static/sitemap'

export default defineNuxtConfig({
    modules: [
        '@nuxtjs/sitemap'
    ]
})
  • 在static目录下创建sitemap.ts文件,文件大致内容如下
import axios from 'axios'

let baseUrl = 'http://www.xxx.com/api/list' // 你要根据数据动态生成链接的接口
let hostUrl = 'http://www.xxx.com' // 前端访问的域名
const sitemap = {
    hostname: hostUrl,
    path: '/sitemap.xml',
    cacheTime: 1000 * 60 * 60 * 24,
    gzip: true,
    generate: false,
    excludeAppSources: true,
    defaults: {
        changefred: 'always',
        lastmod: new Date(),
        priority: 0.8,
    },
    urls: async () => {
        let url = [
            {
                loc: `${hostUrl}/home`,
                changefreq: 'daily',
                lastmod: new Date(),
                priority: 1,
            },
            {
                loc: `${hostUrl}/about`,
                changefreq: 'daily',
                lastmod: new Date(),
                priority: 1,
            }
        ] // 静态的一些链接
        // 通过请求数据动态生成 eg:www.xxx.com/detail?id=1 (页面如果是类似这样的)
        let res = await axios.get(baseUrl, {
            params: {
                page: 1,
                limit: 1000,
            },
        })
        if (res.data.code === 1) { // 根据你后端返回的状态来判断
            let list = res.data.data.list
            let detailList = list.map((item: any) => ({
                loc: `${hostUrl}/detail/?id=${item.id}`,
                changefreq: 'daily',
                priority: 0.9,
            }))
            url = [
                ...url,
                ...detailList,
            ]
        }

        return url
    },
}
export {sitemap}
  • 在nuxt.config.ts中将以上文件引入
import {sitemap} from './static/sitemap'

export default defineNuxtConfig({
    modules: [
        '@nuxtjs/sitemap'
    ],
    sitemap: sitemap
})

       以上步骤完成后,打开浏览器访问 http://localhoost:3000/sitemap.xml 如果正常显示那么就没问题了。


#vue3
#nuxt3
#SEO
#sitemap
#爬虫