关于nextjs中next-sitemap插件生成文件样式丢失问题及自定义样式处理

现象没有默认样式
在这里插入图片描述
在这里插入图片描述
修改后
在这里插入图片描述
在这里插入图片描述
代码配置如下
next-sitemap.config.js如下

// const  { routing } = require('./src/i18n/routing') ;const { flatten } = require('lodash')
const fs = require('fs');
const path = require('path');// 改为硬编码locales值,与routing.ts保持一致
const locales = ['en', 'zh']
module.exports = {siteUrl: process.env.NEXT_PUBLIC_SITE_URL,changefreq: 'weekly',priority: 0.8,sitemapSize: 5000,// generateIndexSitemap: false,transform: async (config, path) => {// 👇 为所有分页文件添加 XSL 声明(包括分页和索引)return {loc: path,lastmod: config.autoLastmod ? new Date().toISOString() : undefined,xsl: '/sitemap-style.xsl'};},// 可选:自定义分页文件名格式filename: 'sitemap-[index].xml',autoLastmod: true, // 从页面文件的修改时间获取generateRobotsTxt: true,exclude: ['/404'// '/admin/*' // 通配符匹配路径],robotsTxtOptions: {policies: [{userAgent: '*', // 所有爬虫allow: '/' // 允许所有路径// disallow: '/private', // 禁止特定路径}],additionalSitemaps: [// process.env.NEXT_PUBLIC_SITE_URL + '/sitemap.xml' // 主站点地图]},// 简化的formatOutput函数,专注于添加样式表引用formatOutput: (sitemapContent) => {console.log('formatOutput正在执行...');// 在XML声明后添加样式表引用const result = sitemapContent.replace('<?xml version="1.0" encoding="UTF-8"?>','<?xml version="1.0" encoding="UTF-8"?>\n<?xml-stylesheet type="text/xsl" href="/sitemap-style.xsl"?>');console.log('formatOutput完成,已添加样式表引用');return result;},additionalPaths: async (config) => {const result = []result.push(locales.map((locale) => {return {loc: process.env.NEXT_PUBLIC_SITE_URL + `/${locale}`,changefreq: 'daily',priority: 1,lastmod: new Date().toISOString(),alternateRefs: locales.filter((targetLocale) => targetLocale === locale).map((targetLocale) => ({href: process.env.NEXT_PUBLIC_SITE_URL + `/${targetLocale}`,hreflang: targetLocale,rel: 'alternate'}))}}) || [])const posts = await fetch(process.env.NEXT_PUBLIC_FETCH_URL + '**************').then((res) => res.json())posts?.data?.map((post) =>result.push(locales.map((locale) => {return {loc: process.env.NEXT_PUBLIC_SITE_URL + `/${locale}/${post.name.toLowerCase()}`,changefreq: 'weekly',priority: 0.8,lastmod: new Date().toISOString(),alternateRefs: locales.filter((targetLocale) => targetLocale === locale).map((targetLocale) => ({href: process.env.NEXT_PUBLIC_SITE_URL + `/${targetLocale}/${post.name.toLowerCase()}`,hreflang: targetLocale,rel: 'alternate'}))}}) || []))const allGames = await fetch(process.env.NEXT_PUBLIC_FETCH_URL + '**************').then((res) => res.json())allGames?.data?.map((post) =>result.push(locales.map((locale) => {return {loc: process.env.NEXT_PUBLIC_SITE_URL + `/${locale}` + '/game/' + `${post.slug}`,changefreq: 'monthly',priority: 0.8,lastmod: new Date().toISOString(),alternateRefs: locales.filter((targetLocale) => targetLocale === locale).map((targetLocale) => ({href: process.env.NEXT_PUBLIC_SITE_URL + `/${targetLocale}` + '/game/' + `${post.slug}`,hreflang: targetLocale,rel: 'alternate'}))}}) || []))return flatten(result)}
}

postbuild.js 处理样式

// 用于处理生成的sitemap文件
const fs = require('fs');
const path = require('path');// 添加站点地图处理逻辑
function processSitemaps() {try {console.log('处理站点地图文件...');const publicDir = path.join(__dirname, 'public');// 确保样式文件存在于public目录const xslSourcePath = path.join(__dirname, 'sitemap-style.xsl');const xslDestPath = path.join(publicDir, 'sitemap-style.xsl');if (fs.existsSync(xslSourcePath)) {fs.copyFileSync(xslSourcePath, xslDestPath);console.log('已复制样式文件到public目录');} else {console.log('警告: 未找到sitemap-style.xsl文件');}// 处理所有站点地图文件const sitemapFiles = fs.readdirSync(publicDir).filter(file => file.startsWith('sitemap') && file.endsWith('.xml'));console.log(`找到 ${sitemapFiles.length} 个站点地图文件`);for (const file of sitemapFiles) {const filePath = path.join(publicDir, file);let content = fs.readFileSync(filePath, 'utf8');if (!content.includes('<?xml-stylesheet')) {console.log(`处理文件: ${file}`);// 替换XML声明,添加样式表引用content = content.replace('<?xml version="1.0" encoding="UTF-8"?>', '<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/sitemap-style.xsl"?>');fs.writeFileSync(filePath, content, {encoding: 'utf8'});console.log(`已更新文件: ${file}`);} else {console.log(`文件 ${file} 已有样式表引用,跳过`);}}console.log('站点地图处理完成');} catch (error) {console.error('处理站点地图文件时出错:', error);}
}// 执行站点地图处理
processSitemaps();

sitemap-style.xsl 样式

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheetversion="2.0"xmlns:xsl="http://www.w3.org/1999/XSL/Transform"xmlns:html="http://www.w3.org/TR/REC-html40"xmlns:sitemap="http://www.sitemaps.org/schemas/sitemap/0.9"xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"xmlns:video="http://www.google.com/schemas/sitemap-video/1.1"xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0"xmlns:xhtml="http://www.w3.org/1999/xhtml"><xsl:output method="html" indent="yes" encoding="UTF-8"/><xsl:template match="/"><html><head><title><xsl:choose><xsl:when test="//sitemap:sitemapindex">Sitemap Index</xsl:when><xsl:otherwise>Sitemap</xsl:otherwise></xsl:choose></title><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><style type="text/css">body {font-family: Arial, sans-serif;font-size: 14px;color: #333;background: #fff;margin: 0;padding: 20px;}h1 {color: #1a73e8;font-size: 24px;margin: 0 0 20px;}table {border-collapse: collapse;width: 100%;margin: 20px 0;border-radius: 6px;overflow: hidden;box-shadow: 0 0 10px rgba(0,0,0,0.1);}th {background-color: #1a73e8;color: #fff;text-align: left;padding: 12px 15px;font-weight: normal;}td {padding: 12px 15px;border-bottom: 1px solid #eee;}tr:hover td {background-color: #f5f5f5;}tr:last-child td {border-bottom: none;}a {color: #1a73e8;text-decoration: none;}a:hover {text-decoration: underline;}.url {max-width: 500px;word-break: break-all;}.count {text-align: center;font-weight: bold;color: #388e3c;font-size: 16px;padding: 10px 0;}.footer {margin-top: 20px;color: #666;font-size: 12px;text-align: center;}</style></head><body><h1><xsl:choose><xsl:when test="//sitemap:sitemapindex">Sitemap Index</xsl:when><xsl:otherwise>Sitemap</xsl:otherwise></xsl:choose></h1><xsl:choose><xsl:when test="//sitemap:sitemapindex"><!-- This is a sitemap index file --><p>This file contains <xsl:value-of select="count(sitemap:sitemapindex/sitemap:sitemap)"/> sitemaps.</p><div class="count">Total Sitemaps: <xsl:value-of select="count(sitemap:sitemapindex/sitemap:sitemap)"/></div><table><tr><th>Sitemap URL</th><th>Last Modified</th></tr><xsl:for-each select="sitemap:sitemapindex/sitemap:sitemap"><tr><td class="url"><a href="{sitemap:loc}"><xsl:value-of select="sitemap:loc"/></a></td><td><xsl:value-of select="sitemap:lastmod"/></td></tr></xsl:for-each></table></xsl:when><xsl:otherwise><!-- This is a sitemap file --><p>This sitemap contains <xsl:value-of select="count(sitemap:urlset/sitemap:url)"/> URLs.</p><div class="count">Total URLs: <xsl:value-of select="count(sitemap:urlset/sitemap:url)"/></div><table><tr><th>URL</th><th>Priority</th><th>Change Frequency</th><th>Last Modified</th></tr><xsl:for-each select="sitemap:urlset/sitemap:url"><tr><td class="url"><a href="{sitemap:loc}"><xsl:value-of select="sitemap:loc"/></a></td><td><xsl:value-of select="sitemap:priority"/></td><td><xsl:value-of select="sitemap:changefreq"/></td><td><xsl:value-of select="sitemap:lastmod"/></td></tr></xsl:for-each></table></xsl:otherwise></xsl:choose>
<!--<div class="footer"><p>Generated by Next.js and next-sitemap</p></div> --></body></html></xsl:template>
</xsl:stylesheet>

存放位置
next-sitemap.config.js和postbuild.js存放根目录,和package.json同级
sitemap-style.xsl和生成的sitemap.xml同一个位置,我放在public目录下

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/80900.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

图片的require问题

问题 <template><!--第一种方式--><img :src"require(/assets/${imageName})" style"width:100px;" /><!--第二种方式--><img :src"require(imageUrl)" style"width:100px;" /> </template><…

【官方题解】StarryCoding 入门教育赛 2 | acm | 蓝桥杯 | 新手入门

比赛传送门&#xff1a; 本场比赛开始时题面存在一些问题&#xff0c;私密马赛&#xff01; A.池化【入门教育赛】 根据题目所给公式计算即可。 #include "bits/stdc.h"signed main() {int t; std::cin >> t;while (t --) {int l, k, s, p; std::cin >&…

课题推荐——低成本地磁导航入门,附公式推导和MATLAB例程运行演示

地磁导航利用地球磁场的自然特性&#xff0c;通过感知磁场变化&#xff0c;帮助机器人或无人设备实现定位和导航。相比于 GPS、激光雷达等导航方法&#xff0c;地磁导航具有以下优势&#xff1a; 低成本&#xff1a;使用地磁传感器&#xff08;如电子罗盘&#xff09;&#xff…

【人工智能】自然语言编程革命:腾讯云CodeBuddy实战5步搭建客户管理系统,效率飙升90%

CodeBuddy 导读一、产品介绍1.1 **什么是腾讯云代码助手&#xff1f;**1.2 插件安装1.2.1 IDE版本要求1.2.2 注意事项1.2.4 插件安装1.2.4.1 环境安装1.2.4.2 安装腾讯云AI代码助手** 1.2.5 功能介绍1.2.5.1 Craft&#xff08;智能代码生成&#xff09;1.2.5.2 Chat&#xff08…

游戏引擎学习第270天:生成可行走的点

回顾并为今天的内容定下基调 今天的计划虽然还不完全确定&#xff0c;可能会做一些内存分析&#xff0c;也有可能暂时不做&#xff0c;因为目前并没有特别迫切的需求。最终我们会根据当下的状态随性决定&#xff0c;重点是持续推动项目的进展&#xff0c;无论是 memory 方面还…

Java反射详细介绍

的反射&#xff08;Reflection&#xff09;是一种强大的机制&#xff0c;允许程序在运行时动态获取类的信息、操作类的成员&#xff08;属性、方法、构造器&#xff09;&#xff0c;甚至修改类的行为。它是框架开发&#xff08;如 Spring、MyBatis&#xff09;、单元测试工具&a…

c语言第一个小游戏:贪吃蛇小游戏05

贪吃蛇脱缰自动向右走&#xff1a;脱缰的野蛇 #include <curses.h> #include <stdlib.h> struct snake{ int hang; int lie; struct snake *next; }; struct snake *head; struct snake *tail; void initNcurse() { initscr(); keypad(stdscr,1); } int …

react-diff-viewer 如何实现语法高亮

前言 react-diff-viewer 是一个很好的 diff 展示库&#xff0c;但是也有一些坑点和不完善的地方&#xff0c;本文旨在描述如何在这个库中实现自定义语法高亮。 Syntax highlighting is a bit tricky when combined with diff. Here, React Diff Viewer provides a simple rend…

coco数据集mAP评估

0 coco数据集划分说明 1 用yolo自带的评估 from ultralytics import YOLOmodel YOLO("../spatial-perception/checkpoints/yolo11n.pt")metrics model.val(data"./coco.yaml", save_jsonTrue) ## save_json为True,可以把预测结果存成json文件&#xff…

sensitive-word-admin v2.0.0 全新 ui 版本发布!vue+前后端分离

前言 sensitive-word-admin 最初的定位是让大家知道如何使用 sensitive-word&#xff0c;所以开始想做个简单的例子。 不过秉持着把一个工具做好的原则&#xff0c;也收到很多小伙伴的建议。 v2.0.0 在 ruoyi-vue&#xff08;也非常感谢若依作者多年来的无私奉献&#xff09…

好消息!PyCharm 社区版现已支持直接选择 WSL 终端为默认终端

在过去&#xff0c;PyCharm 社区版虽然提供了链接 Windows 子系统 Linux&#xff08;WSL&#xff09;终端的能力&#xff0c;但用户无法在设置中直接指定 WSL 为默认终端&#xff0c;这一功能仅限于专业版使用者。 而现在&#xff0c;在 PyCharm 2025.1.1 版本中&#xff0c;Je…

【Redis】string 字符串

文章目录 string 字符串常用命令设置和获取setgetmget & mset 计数操作incr & incrbydecr & decrbyincrbyfloat 字符串操作appendstrlengetrangesetrange 应用场景 string 字符串 关于 Redis 的字符串&#xff0c;有几点需要注意 Redis 所有的 key 的类型都是字符…

本地部署firecrawl的两种方式,自托管和源码部署

网上资料很多 AI爬虫黑科技 firecrawl本地部署-CSDN博客 源码部署 前提条件本地安装py&#xff0c;node.js环境,嫌弃麻烦直接使用第二种 使用git或下载压缩包 git clone https://github.com/mendableai/firecrawl.git 设置环境参数 cd /firecrawl/apps/api 复制环境参数 …

(三)毛子整洁架构(Infrastructure层/DapperHelper/乐观锁)

文章目录 项目地址一、Infrastructure Layer1.1 创建Application层需要的服务1. Clock服务2. Email 服务3. 注册服务 1.2 数据库服务1. 表配置Configurations2. Respository实现3. 数据库链接Factory实现4. Dapper的DataOnly服务实现5. 所有数据库服务注册 1.3 基于RowVersion的…

uni-app微信小程序登录流程详解

文章目录 uni-app微信小程序登录流程实战详解微信小程序登录流程概述1. 获取登录凭证&#xff08;code&#xff09;2. 发送登录请求3. 保存登录态4. 登录状态管理5. 应用登录状态请求拦截器中添加 token自动登录页面路由守卫 使用 Vuex 集中管理登录状态登录组件示例登录流程最…

GUC并发编程和SpringCloud,二者之间的关系

一.提问 我认为&#xff0c;Java开发中&#xff0c;如果项目的每一个小模块需要不同人员并行开发时&#xff0c;就需要使用SpringCloud&#xff1b;如果要解决系统用户激增&#xff0c;就是用GUC并发编程。 这个说法对么&#xff1f; 二.解答 你的理解部分正确&#xff0c;但不…

在 Vue 3 中使用 canvas-confetti 插件

&#x1f389; 在 Vue 3 中使用 canvas-confetti 插件 canvas-confetti 是一个轻量、无依赖的 JavaScript 动画库&#xff0c;用于在网页上展示彩带、庆祝动画。非常适合用于抽奖、支付成功、活动庆祝等场景。 本教程将指导你如何在 Vue 3 项目中集成并使用该插件。 &#x1…

深入解析Spring Boot项目目录结构:从新手到规范实践

一、标准项目结构全景图 典型的Spring Boot项目&#xff08;Maven构建&#xff09;目录结构如下&#xff1a; my-spring-project/ ├── src/ │ ├── main/ │ │ ├── java/ # 核心代码 │ │ │ └── com/ │ │ │ └── exa…

【C语言】宏经典练习题,交换奇偶位

交换奇偶位 写一个宏&#xff0c;可以将一个整数的二进制位的奇数位和偶数位交换。 #define Swap(x) x(((x&0x55555555)<<1)((x&0xaaaaaaaa)>>1)) int main() {int a 10;Swap(a);printf("%d\n", a);return 0; } 写宏的思路&#xff1a; 假设…

VSCode-插件:codegeex:ai coding assistant / 清华智普 AI 插件

一、官网 https://codegeex.cn/ 二、vscode 安装插件 点击安装即可&#xff0c;无需复杂操作&#xff0c;国内软件&#xff0c;无需科学上网&#xff0c;非常友好 三、智能注释 输入 // 或者 空格---后边自动出现注释信息&#xff0c;&#xff0c;按下 Tab 键&#xff0c;进…