使用 Nextjs 创建现代网站的技巧
Source: Dev.to
使用 App Router(Next.js 13+)
Next.js 13 引入了 App Router,相较于 Pages Router 更加强大。其优势包括:
- 默认使用 Server Components —— 更快且更高效
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<>
{children}
</>
);
}
使用 Metadata API 优化 SEO
Next.js 提供了 Metadata API,可以非常轻松地为每个页面设置 SEO。
// app/page.tsx
import { Metadata } from 'next';
export const metadata: Metadata = {
title: '页面标题',
description: '页面简短描述,用于 SEO',
// 可添加其他属性,如 openGraph、twitter 等。
};
使用 next/image 优化图片
使用 next/image 组件实现图片的自动优化(懒加载、尺寸调整以及现代格式)。
import Image from 'next/image';
export default function Hero() {
return (
<Image
src="/path/to/image.jpg"
alt="图片描述"
width={800}
height={600}
/>
);
}
确保图片尺寸与访问设备相匹配。
设置 Sitemap 与 robots.txt
在 app/sitemap.ts 中创建动态生成 sitemap 的文件。
// app/sitemap.ts
import { MetadataRoute } } from 'next';
export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: 'https://website-kamu.com',
lastModified: new Date(),
},
{
url: 'https://website-kamu.com/about',
lastModified: new Date(),
},
// 根据需求添加其他路由
];
}
将 robots.txt 放在公共文件夹 (public/robots.txt) 中,例如:
User-agent: *
Allow: /
Sitemap: https://website-kamu.com/sitemap.xml
使用 TypeScript
TypeScript 能让开发更顺畅,减少错误。
// types/index.ts
export interface Project {
id: string;
title: string;
description: string;
image: string;
}
// components/ProjectCard.tsx
import { Project } from '@/types';
interface Props {
project: Project;
}
export default function ProjectCard({ project }: Props) {
return (
<div className="project-card">
<h3>{project.title}</h3>
<p>{project.description}</p>
{/* 使用 next/image 显示 project.image */}
</div>
);
}
使用 Vercel 部署(将代码推送到 GitHub)
Vercel 对 Next.js 有专门的优化,能够让你的网站拥有极佳的性能。
- 将仓库推送到 GitHub。
- 将仓库连接到 Vercel。
- 每当主分支有更改时,Vercel 会自动构建并部署。
✅ 优势: 高性能、自动预览以及简洁的 CI/CD 集成。
祝编码愉快! 🚀