Next.js中生成sitemap的简单方法

首先,让我们设置项目结构:

lua 复制代码
my-nextjs-app/
  ├── app/
  │   ├── page.tsx
  │   └── server-sitemap.xml/
  │       └── route.ts
  ├── public/
  ├── next-sitemap.config.js
  ├── package.json
  └── tsconfig.json

1. 安装依赖

在项目根目录运行以下命令:

bash 复制代码
npm install next-sitemap

2. 配置next-sitemap

创建next-sitemap.config.js文件:

typescript 复制代码
/** @type {import('next-sitemap').IConfig} */
module.exports = {
  siteUrl: process.env.SITE_URL || 'https://example.com',
  generateRobotsTxt: true,
  exclude: ['/server-sitemap.xml'],
  robotsTxtOptions: {
    additionalSitemaps: [
      'https://example.com/server-sitemap.xml',
    ],
  },
}

3. 更新package.json

在package.json中添加postbuild脚本:

json 复制代码
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "postbuild": "next-sitemap",
    "start": "next start"
  }
}

4. 创建动态sitemap

在app/server-sitemap.xml/route.ts文件中:

typescript 复制代码
import { getServerSideSitemap } from 'next-sitemap'

export async function GET() {
  // 这里可以从CMS或数据库获取动态URL
  const posts = await fetchPostsFromDatabase()

  return getServerSideSitemap([
    {
      loc: 'https://example.com',
      lastmod: new Date().toISOString(),
    },
    {
      loc: 'https://example.com/about',
      lastmod: new Date().toISOString(),
    },
    ...posts.map((post) => ({
      loc: `https://example.com/blog/${post.slug}`,
      lastmod: post.updatedAt.toISOString(),
    })),
  ])
}

async function fetchPostsFromDatabase() {
  // 模拟从数据库获取文章
  return [
    { slug: 'first-post', updatedAt: new Date('2025-02-20') },
    { slug: 'second-post', updatedAt: new Date('2025-02-21') },
  ]
}

5. 示例页面

在app/page.tsx中:

typescript 复制代码
export default function Home() {
  return (
    <main>
      <h1>欢迎来到我的Next.js网站</h1>
      <p>这是一个使用next-sitemap生成sitemap的示例。</p>
    </main>
  )
}

6. 生成sitemap

运行构建命令:

bash 复制代码
npm run build

这将构建您的Next.js应用程序,然后运行next-sitemap来生成静态sitemap和robots.txt文件。

生成的文件将位于public目录中:

  • public/sitemap.xml
  • public/sitemap-0.xml
  • public/robots.txt

同时,动态生成的sitemap可以通过/server-sitemap.xml路径访问。

这个设置将为您的Next.js应用程序创建一个全面的sitemap解决方案,包括静态页面和动态生成的内容

相关推荐
天空属于哈夫克35 天前
企业微信二次开发:精准实现关键词自动回复
架构·企业微信
子兮曰5 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰5 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
前端小万5 天前
写公众号赚了 3000 块后,我做了一款叫 "一键成稿" 的软件
前端·微信小程序
爱勇宝5 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
三十而立洋5 天前
Cookie 详解:从产生到安全,一次讲透
前端·javascript
晨米酱5 天前
AGENTS.md:Agent 的上下文策略层
面试·架构·agent
这个DBA有点耶5 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
卡布鲁5 天前
把一个 Vite + Vue3 应用塞进 qiankun (React + Umi3) 主站:十个坑的复盘
前端·javascript·react.js
码流子5 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构