yarn add @nuxtjs/sitemap -D
npm i @nuxtjs/sitemap -D
cnpm i @nuxtjs/sitemap -D 在项目根目录下找到 nuxt.config.js 往modules 添加'@nuxtjs/sitemap' 在项目目录下新建config 文件夹,创建sitemap.js 文件写入在nuxt.config.js 导入sitemap.js 。并添加 sitemap 项,在浏览器输入项目的sitemap地址即可解决nuxt生成的sitemap.xml文件日期格式问题(YYYY-MM-DD)使用dayjs格式化时间,如果出现格式化时间还是显示ISO时间格式那么需要到sitemap源码查看时间是否被转换了! 找到@nuxtjs/sitemap包, 注释掉smi.lastmod = (new Date(smiLoose.lastmod)).toISOString(); 在node_modules\sitemap\dist\lib\sitemap.js 注释上面的代码,因为他会自动把时间转换成ISO-8601时间格式。 如果没有找到node_modules\sitemap\dist\lib\sitemap.js ,那就从node_modules\@nuxtjs 文件夹里找.
如何生成多个sitemap.xml文件?在 ./config/sitemap.js 中定义的sitemap 使用数组形式.
const sitemap = [
{
path: '/sitemap.xml', // 生成的文件路径
hostname: 'https://baidu.com/', // 网址
cacheTime: 1000 * 60 * 60 * 24, // 1天 更新频率,只在 generate: false有用
gzip: true, // 生成 .xml.gz 压缩的 sitemap
generate: false, // 允许使用 nuxt generate 生成
// 排除不要页面
exclude: [
'/404' // 这里的路径相对 hostname
],
// xml默认的配置
defaults: {
changefreq: 'always',
lastmod: new Date()
},
// 需要生成的xml数据, return 返回需要给出的xml数据
routes: () => {
const routes = [
{
url: "/", // 这里的路径相对 hostname
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, // 1天 更新频率,只在 generate: false有用
gzip: true, // 生成 .xml.gz 压缩的 sitemap
generate: false, // 允许使用 nuxt generate 生成
// 排除不要页面
exclude: [
'/404' // 这里的路径相对 hostname
],
// xml默认的配置
defaults: {
changefreq: 'always',
lastmod: new Date()
},
// 需要生成的xml数据, return 返回需要给出的xml数据
routes: () => {
const routes = [
{
url: "/test", // 这里的路径相对 hostname
changefreq: "always",
lastmod: new Date()
},
{
url: "/test/helloword",
changefreq: "always",
lastmod: "2020-12-04"
}
]
return routes
}
}
]
export default sitemap 和后端配合生成更多的url数据 拼接url,使用axios请求获取列表数据等等....重写sitemap.js,使用请求获取url数据
import axios from "axios"
const sitemap = {
path: '/sitemap.xml', // 生成的文件路径
hostname: 'https://baidu.com/', // 网址
cacheTime: 1000 * 60 * 60 * 24, // 1天 更新频率,只在 generate: false有用
gzip: true, // 生成 .xml.gz 压缩的 sitemap
generate: false, // 允许使用 nuxt generate 生成
// 排除不要页面
exclude: [
'/404' // 这里的路径相对 hostname
],
// xml默认的配置
defaults: {
changefreq: 'always',
lastmod: new Date()
},
// 需要生成的xml数据, return 返回需要给出的xml数据
routes: async () => {
// 从后台获取数据,拼接url生成更多的xml数据
const getUrl = 'https://******'
const { data } = await axios.get(getUrl)
const routes = [
{
url: "/", // 这里的路径相对 hostname
changefreq: "always",
lastmod: new Date()
},
{
url: "/helloword",
changefreq: "always",
lastmod: "2020-12-04"
}
]
if (data && data.list) {
let arr = data.list.map(item => ({
url: "/blog/" + item.id,
lastmod: item.update_time,
changefreq: "yearly"
}))
routes.concat(arr)
}
return routes
}
}
export default sitemap
|