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解决方案,包括静态页面和动态生成的内容

相关推荐
hunterandroid10 小时前
[Android 从零到一] Compose LazyColumn 性能优化:key、稳定性与重组治理
android·前端
lichenyang45310 小时前
从一次团队邀请开始:用 React、NestJS 与 Socket.IO 做可靠的实时通知
前端
vtian10 小时前
一篇文章吃透 Monorepo:pnpm + Turborepo + Changesets 全流程实战(含 8 个踩坑)
前端
默_笙10 小时前
❗ 点击计数按钮,为什么"峨眉队"也跟着重新渲染?React.memo 说:我记住了
前端·javascript
lucky_syq10 小时前
第5篇 · S1·下:前沿架构:MoE、Reasoning 模型、长上下文、多模态、SSM/Mamba 与模型谱系
人工智能·学习·架构
315356691311 小时前
DeepSeek Harness 发布后,我没急着跑 Demo,先把 `.agents/` 翻了一遍
前端·后端·github
名字还没想好☜11 小时前
Next.js 用 Server Components 直连数据库:去掉 API 层的边界,和三条别踩的安全红线
前端·javascript·数据库·安全·react·next.js
学习zhao极致it11 小时前
2020全新React教程全家桶实战redux+antd+React Hooks前端js视频
前端
用户9210802628611 小时前
Bubble 消息操作区改造:复制、重新生成和反馈
前端
LEE11 小时前
AI Agent 都在疯狂加功能,它说:我全砍了
前端·后端