nuxt使用@nuxtjs/sitemap生成sitemap.xml

BG7ZAG

分类: 程序开发、网站建设 0 5

依赖于@nuxtjs/sitemap 和 axios ,如果是少量静态页面的话则不需要axios

先安装@nuxtjs/sitemap插件:

yarn add @nuxtjs/sitemap axios

然后在 nuxt.config.js 中添加配置

sitemap: {
    path: '/sitemap.xml', // sitemap文件名,不用改
    hostname: 'https://xn--nf1a578axkh.xn--fiqs8s/', // 网址
    cacheTime: 1000 * 60 * 60 * 24, // 更新频率,只在 generate: false有用
    gzip: true, // 生成 .xml.gz 压缩的 sitemap
    generate: false, // 允许使用 nuxt generate 生成
    // 排除不要页面
    exclude: [
      '/404'
    ],
    // 页面路由
    routes (callback) {
      axios.all([
        // blog 分类
        axios.get('https://blogapi.bg7zag.com/wp-json/xm-blog/v1/menu'),
        // 文章列表
        axios.get('https://blogapi.bg7zag.com/wp-json/wp/v2/posts', {
          params: {
            page: 1,
            per_page: 100,
            _embed: true
          },
          data: { progress: false }
        }),
        // 标签
        axios.get('https://blogapi.bg7zag.com/wp-json/xm-blog/v1/info')

      ]).then(axios.spread(function (menu, posts, info) {
        let now = new Date();
        now.setHours(now.getHours(), now.getMinutes() - now.getTimezoneOffset());
        let indexRoutes = [
          {
            url: '/',
            changefreq: 'daily',
            priority: 1,
            lastmodISO: now.toISOString()
          }
        ]
        let menuRoutes = menu.data.mainMenu.map((data) => {
          let url = ''
          if (data.object === 'category') {
            url = '/category/1?type=' + data.object_id + '&title=' + data.title
          }
          if (data.object === 'page') {
            url = '/page/' + data.object_id
          }
          if (data.object === 'post_tag') {
            url = '/tags/1?type=' + data.term_id + '&title=' + data.name
          }
          if (data.object === 'custom') {
            url = data.url
          }
          return {
            url: url,
            changefreq: 'monthly',
            priority: 0.8,
            lastmodISO: data.post_modified
          }
        });
        let postsRoutes = posts.data.map((data) => {
          return {
            url: '/' + data.id,
            changefreq: 'daily',
            priority: 0.9,
            lastmodISO: data.modified
          }
        });
        let tagsRoutes = info.data.tagCloud.map((data) => {
          return {
            url: `/tags/1?type=${data.term_id}&title=${data.name}`,
            changefreq: 'weekly',
            priority: 0.7,
            lastmodISO: now
          }
        })
        // 用 concat 進行合併
        callback(null, indexRoutes.concat(menuRoutes, postsRoutes, tagsRoutes));
      }), function (err) {
        throw (err);
      });
    }
  }

参考文献:Nuxt教學:快速建立Nuxt網站地圖 Sitemap

  • 4人 Love
  • 2人 Haha
  • 0人 Wow
  • 0人 Sad
  • 0人 Angry

作者简介: BG7ZAG

打赏

博客站长,前端开发工程师

共 5 条评论关于 “nuxt使用@nuxtjs/sitemap生成sitemap.xml”

Loading...