首先,让我们设置项目结构:
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解决方案,包括静态页面和动态生成的内容