用Remix构建全栈应用:比Next.js更简洁的“Web标准优先“框架

用Remix构建全栈应用:比Next.js更简洁的“Web标准优先“框架
用Remix构建全栈应用比Next.js更简洁的Web标准优先框架Remix的设计哲学回归Web基础Next.js是React框架而Remix是Web框架——它的设计哲学是用Web标准HTML、HTTP、浏览器API而非框架抽象。核心差异数据加载方式Next.js的useEffectuseState模式// Next.js客户端获取数据 use client; import { useEffect, useState } from react; export function Posts() { const [posts, setPosts] useState([]); const [loading, setLoading] useState(true); useEffect(() { fetch(/api/posts).then(res res.json()).then(data { setPosts(data); setLoading(false); }); }, []); if (loading) return div加载中.../div; return ul{posts.map(p li key{p.id}{p.title}/li)}/ul; }Remix的loaderuseLoaderData模式// Remix服务端获取数据同构渲染 import { useLoaderData } from remix-run/react; import { json } from remix-run/node; import { loader as postsLoader } from ~/routes/api.posts; export async function loader() { const posts await db.posts.findMany(); return json(posts); } export default function Posts() { const posts useLoaderDatatypeof loader(); return ul{posts.map(p li key{p.id}{p.title}/li)}/ul; }关键优势无loading状态数据在服务端获取HTML直接包含内容——用户不会看到加载中SEO友好搜索引擎看到的HTML包含完整内容代码更简洁不需要useEffectuseStateloading状态Remix核心概念Loader、Action、FormLoader数据加载器处理GET请求每个路由模块可以导出loader函数——它在服务端执行返回该路由需要的数据。// app/routes/posts.$postId.tsx import { json, type LoaderFunction } from remix-run/node; import { useLoaderData } from remix-run/react; export async function loader({ params }: { params: { postId: string } }) { const post await db.posts.findUnique({ where: { id: params.postId } }); if (!post) throw new Response(Not Found, { status: 404 }); return json(post); } export default function Post() { const post useLoaderDatatypeof loader(); return ( article h1{post.title}/h1 div dangerouslySetInnerHTML{{ __html: post.content }} / /article ); }Action数据变更器处理POST/PUT/DELETE请求// app/routes/posts/new.tsx import { json, type ActionFunction } from remix-run/node; import { redirect } from remix-run/node; import { useActionData } from remix-run/react; export async function action({ request }: { request: Request }) { const formData await request.formData(); const title formData.get(title); const content formData.get(content); if (!title) { return json({ error: 标题不能为空 }, { status: 400 }); } const post await db.posts.create({ data: { title, content } }); return redirect(/posts/${post.id}); } export default function NewPost() { const actionData useActionDatatypeof action(); return ( form methodpost div label标题/label input nametitle / {actionData?.error p classtext-red-500{actionData.error}/p} /div div label内容/label textarea namecontent / /div button typesubmit创建/button /form ); }关键特性Remix的form是增强版的HTML Form——它用JavaScript增强SPA体验但如果不加载JS仍然是正常表单提交渐进增强。嵌套路由Nested Routes最优的UI组合模式Remix的路由系统是文件路径即路由且支持嵌套布局。文件结构app/routes/ ├── _index.tsx # 首页 / ├── about.tsx # 关于页 /about ├── posts/ │ ├── _index.tsx # 文章列表 /posts │ ├── $postId.tsx # 文章详情 /posts/123 │ └── new.tsx # 新建文章 /posts/new └── dashboard/ ├── _layout.tsx # Dashboard布局侧边栏顶栏 ├── _index.tsx # Dashboard首页 /dashboard └── settings.tsx # 设置页 /dashboard/settings嵌套路由的效果当URL是/dashboard/settings时dashboard/_layout.tsx渲染显示侧边栏dashboard/settings.tsx渲染在_layout.tsx的Outlet /位置// app/routes/dashboard/_layout.tsx import { Outlet, Link } from remix-run/react; export default function DashboardLayout() { return ( div classflex h-screen {/* 侧边栏始终显示 */} aside classw-64 bg-gray-100 p-4 Link to/dashboard首页/Link Link to/dashboard/settings设置/Link /aside {/* 主内容区随URL变化 */} main classflex-1 p-6 Outlet / /main /div ); }优势切换/dashboard/settings到/dashboard/profile时侧边栏不会重新渲染——这提升了用户体验和性能。错误处理ErrorBoundaryRemix每个路由都可以定义ErrorBoundary——当loader或组件抛出错误时显示该路由专属的错误UI。// app/routes/posts.$postId.tsx export async function loader({ params }: { params: { postId: string } }) { const post await db.posts.findUnique({ where: { id: params.postId } }); if (!post) throw new Response(Post not found, { status: 404 }); return json(post); } export default function Post() { // ... } // 错误边界UI export function ErrorBoundary({ error }: { error: Error }) { return ( div classp-6 text-center h1 classtext-2xl text-red-600出错了/h1 p{error.message}/p a href/posts classtext-blue-600返回文章列表/a /div ); }关键ErrorBoundary是该路由的一部分——侧边栏、导航栏仍然显示只有内容区显示错误。这比整个页面白屏好得多。实战用Remix Prisma Tailwind构建博客平台第一步初始化Remix项目npx create-remixlatest # 选择 # - Template: Remix App Server (Node.js) # - TypeScript: Yes # - Tailwind CSS: Yes cd my-blog npm install第二步配置Prismanpm install prisma prisma/client npx prisma init// prisma/schema.prisma model Post { id String id default(cuid()) title String content String published Boolean default(false) createdAt DateTime default(now()) updatedAt DateTime updatedAt }第三步实现文章列表页带分页// app/routes/posts._index.tsx import { json, type LoaderFunction } from remix-run/node; import { useLoaderData, Link } from remix-run/react; import { prisma } from ~/lib/prisma; export async function loader({ request }: { request: Request }) { const url new URL(request.url); const page parseInt(url.searchParams.get(page) || 1); const pageSize 10; const [posts, total] await Promise.all([ prisma.post.findMany({ where: { published: true }, orderBy: { createdAt: desc }, skip: (page - 1) * pageSize, take: pageSize, }), prisma.post.count({ where: { published: true } }), ]); return json({ posts, page, totalPages: Math.ceil(total / pageSize), }); } export default function Posts() { const { posts, page, totalPages } useLoaderDatatypeof loader(); return ( div classmax-w-4xl mx-auto p-6 h1 classtext-3xl font-bold mb-8文章列表/h1 ul classspace-y-4 {posts.map(post ( li key{post.id} classborder-b pb-4 Link to{/posts/${post.id}} classtext-xl text-blue-600 hover:underline {post.title} /Link p classtext-gray-500 text-sm mt-1 {new Date(post.createdAt).toLocaleDateString(zh-CN)} /p /li ))} /ul {/* 分页 */} div classmt-8 flex gap-2 {page 1 ( Link to{/posts?page${page - 1}} classpx-4 py-2 bg-gray-200 rounded 上一页 /Link )} {page totalPages ( Link to{/posts?page${page 1}} classpx-4 py-2 bg-gray-200 rounded 下一页 /Link )} /div /div ); }第四步实现文章创建带表单验证// app/routes/posts.new.tsx import { json, redirect, type ActionFunction } from remix-run/node; import { useActionData, Form } from remix-run/react; export async function action({ request }: { request: Request }) { const formData await request.formData(); const title formData.get(title) as string; const content formData.get(content) as string; const errors: Recordstring, string {}; if (!title || title.length 3) errors.title 标题至少3个字符; if (!content || content.length 10) errors.content 内容至少10个字符; if (Object.keys(errors).length 0) { return json({ errors }, { status: 400 }); } const post await prisma.post.create({ data: { title, content, published: true }, }); return redirect(/posts/${post.id}); } export default function NewPost() { const actionData useActionDatatypeof action(); return ( div classmax-w-2xl mx-auto p-6 h1 classtext-3xl font-bold mb-6新建文章/h1 Form methodpost classspace-y-4 div label classblock mb-1标题/label input nametitle classw-full p-2 border rounded / {actionData?.errors?.title ( p classtext-red-500 text-sm mt-1{actionData.errors.title}/p )} /div div label classblock mb-1内容/label textarea namecontent rows{10} classw-full p-2 border rounded / {actionData?.errors?.content ( p classtext-red-500 text-sm mt-1{actionData.errors.content}/p )} /div button typesubmit classbg-blue-600 text-white px-6 py-2 rounded 发布 /button /Form /div ); }部署从本地到生产环境部署到Node.js服务器如Fly.io、Railway# 构建 npm run build # 启动Remix App Server npm start部署到Vercel/NetlifyServerlessRemix官方支持Serverless部署。在remix.config.js里设置// remix.config.js module.exports { serverBuildTarget: vercel, // 或 netlify };然后用Vercel CLI部署vercel deploy结论Remix适合你吗✅适合场景需要全栈应用数据加载 表单提交 错误处理偏好Web标准HTML Form、HTTP方法、浏览器API想要更简洁的代码相比Next.js的useEffectuseState❌不适合场景纯静态网站选Astro需要复杂的客户端状态管理选Next.js Redux/Zustand团队不熟悉服务端渲染学习曲线较陡独立开发者的实战建议如果你在做内容管理系统CMS、Dashboard、表单密集型应用**Remix是比Next.js更好的选择——它的表单处理和错误处理更简洁、更健壮。下一步把你的Next.js应用里表单密集的页面用Remix重写——你会立即感受到代码量减30%用户体验更流畅。