本文共 2691 字,大约阅读时间需要 8 分钟。
安装使用步骤:
@nuxtjs/sitemap
:yarn add @nuxtjs/sitemap -D
打开nuxt.config.js
,将modules
数组中添加'@nuxtjs/sitemap'
。
创建config
文件夹,并在其中新建sitemap.js
文件,内容如下:
const sitemap = [ { path: '/sitemap.xml', hostname: 'https://baidu.com', cacheTime: 1000 * 60 * 60 * 24, gzip: true, generate: false, exclude: ['/404'], defaults: { changefreq: 'always', lastmod: new Date() }, routes: () => { const routes = [ { url: '/', changefreq: 'always', lastmod: new Date() }, { url: '/helloword', changefreq: 'always', lastmod: '2020-12-04' } ]; return routes; } }];export default sitemap;
nuxt.config.js
中导入sitemap.js
,并添加sitemap
项。解决日期格式问题:
node_modules/sitemap/dist/lib/sitemap.js
,注释掉smi.lastmod = (new Date(smiLoose.lastmod)).toISOString();
,以确保生成的日期格式为YYYY-MM-DD
。生成多个sitemap.xml文件:
config/sitemap.js
,将sitemap
设置为数组形式:const sitemap = [ { path: '/sitemap.xml', hostname: 'https://baidu.com', cacheTime: 1000 * 60 * 60 * 24, gzip: true, generate: false, exclude: ['/404'], defaults: { changefreq: 'always', lastmod: new Date() }, routes: () => { const routes = [ { url: '/', changefreq: 'always', lastmod: new Date() }, { url: '/helloword', changefreq: 'always', lastmod: '2020-12-04' } ]; return routes; } }, { path: '/test/sitemap.xml', hostname: 'https://baidu.com', cacheTime: 1000 * 60 * 60 * 24, gzip: true, generate: false, exclude: ['/404'], defaults: { changefreq: 'always', lastmod: new Date() }, routes: () => { const routes = [ { url: '/test', changefreq: 'always', lastmod: new Date() }, { url: '/test/helloword', changefreq: 'always', lastmod: '2020-12-04' } ]; return routes; } }];export default sitemap;
结合后端数据生成sitemap.xml:
sitemap.js
中引入axios
,并修改routes
函数:import axios from 'axios';const sitemap = [ { path: '/sitemap.xml', hostname: 'https://baidu.com', cacheTime: 1000 * 60 * 60 * 24, gzip: true, generate: false, exclude: ['/404'], defaults: { changefreq: 'always', lastmod: new Date() }, routes: async () => { const getUrl = 'https://******'; const { data } = await axios.get(getUrl); const routes = [ { url: '/', changefreq: 'always', lastmod: new Date() }, { url: '/helloword', changefreq: 'always', lastmod: '2020-12-04' } ]; if (data && data.list) { const arr = data.list.map(item => ({ url: `/blog/${item.id}`, lastmod: item.update_time, changefreq: 'yearly' })); routes.concat(arr); } return routes; } }];export default sitemap;
转载地址:http://mqdyz.baihongyu.com/