關于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.pswp.cn/bicheng/80900.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/80900.shtml
英文地址,請注明出處:http://en.pswp.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;進…