使用Next.js构建单页面React应用

发布于:2025-05-01 ⋅ 阅读:(41) ⋅ 点赞:(0)

最近遇到一个问题 突然要一个单页面的项目 用惯了Next.js 而 create-react-app 又不推荐且不灵活 最终找发现Nextjs也支持单页面应用 以下是使用Next.js构建单页面React应用过程

1 正常创建项目 (我选择的是Pages Router 而非 AppRoute)
2 修改配置文件
next.config.ts

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
    output: "export",
    distDir: "dist", //默认打包后目录名 `build`
};

export default nextConfig;

3 删除 src/api 目录 单页面应用 不支持api路由功能 放着会警告

两个常用页面 尝试
index.tsx

import Link from "next/link";
import { useRouter } from "next/router";

export default function Home() {
    const router = useRouter();

    // 编程式导航示例
    const goToAbout = () => {
        router.push("/about"); // 客户端跳转
    };

    return (
        <div>
            <h1>SPA Home Page</h1>
            {/* 声明式导航 */}
            <Link href='/about'>
                About Page
            </Link>
            {/* 编程式导航 */}
            <button onClick={goToAbout}>Go to About</button>
        </div>
    );
}

about.tsx

import Link from "next/link";
import { useRouter } from "next/router";

export default function AboutPage() {
    const router = useRouter();

    const goToAbout = () => {
        router.push("/");
    };

    return (
        <div>
            <h1>SPA AboutPage</h1>
            <Link href='/'>Home Page</Link>
            <button onClick={goToAbout}>Go to Home</button>
        </div>
    );
}

在两个页面间跳转 发现已经不需加载 实现了单页面应用


网站公告

今日签到

点亮在社区的每一天
去签到