字节笔记本
2026年2月18日
8 个让 Next.js 开发更轻松的优秀库
本文介绍 8 个让 Next.js 开发更轻松的优秀库,涵盖类型安全、表单处理、状态管理、数据获取等方面,帮助你快速构建高质量的 React 应用。
文章简介
Next.js 已成为构建 React 应用的默认框架,它提供了对页面构建方式的精细控制,以及灵活的数据获取策略。本文作者是 Flavien Bonvin,他分享了在实际项目中必装的 Next.js 库,这些库经过两年多的生产环境验证。
必装库清单
1. TypeScript
虽然不是库,但 TypeScript 已成为现代 React 开发的标配。它是 JavaScript 的类型化超集,帮助开发者描述数据结构,编写更安全的代码。
interface Person {
firstName: string;
lastName?: string; // 可选字段
email: string;
username: string;
age?: number;
}
const getUserNameInfo = (person: Person) => {
// TypeScript 会在编译时捕获这些错误
const lastNameLength = person.lastName.length; // 错误:可能为 undefined
return `${person.username} is ${person.age > 18 ? "adult" : "not adult"}`;
};安装命令:
npm install typescript --save-dev
yarn add typescript --dev
pnpm add -D typescript文档: TypeScript 官网
2. npm-check-updates
全局安装的工具,用于检查和管理依赖更新。
功能:
ncu- 列出可更新的包ncu -u- 自动更新所有包ncu -i- 交互式选择更新(推荐)
安装命令:
npm install -g npm-check-updates
yarn global add npm-check-updates注意: pnpm 用户可直接使用
pnpm outdated和pnpm upgrade -i
文档: GitHub - npm-check-updates
3. Chakra UI
组件库的选择因人而异,但 Chakra UI 是作者团队从 Ant Design 迁移后的首选。
优势:
- 组件质量高、易于定制
- 原生支持响应式设计
- 基于 CSS 知识构建,不依赖 Bootstrap 式栅格系统
- 与 react-hook-form 完美配合
为什么选择 Chakra UI 而不是 Tailwind?
- 团队对组件库更熟悉
- 预构建组件加速开发
- 学习曲线相对平缓
文档: Chakra UI 官网
4. react-hook-form
表单处理是 React 开发中较繁琐的部分,react-hook-form 让这一过程变得愉快。
特点:
- 与 Formik 相比,API 更简洁易读
- 与任何 UI 组件库兼容
- 官方 YouTube 频道提供详细教程
使用示例:
type FormData = {
firstName: string;
lastName: string;
age: number;
};
const RegistrationForm = () => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<FormData>();
const onSubmit: SubmitHandler<FormData> = (data) => console.log(data);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} />
<input {...register("lastName", { required: true })} />
{errors.lastName && <p>Last name is required.</p>}
<input {...register("age", { pattern: /\d+/ })} />
{errors.age && <p>Please enter number for age.</p>}
<input type="submit" />
</form>
);
};安装命令:
npm i react-hook-form
yarn add react-hook-form
pnpm add react-hook-form5. Zod
Schema 验证库,彻底改变 API 数据验证的方式。
核心功能:
- 定义数据 Schema
- 自动验证和类型推断
- 替代手动构建类和构造函数
使用示例:
import { z } from "zod";
export const userSchema = z.object({
id: z.string(),
firstName: z.string().nullable(), // string | null
lastName: z.string().nullable(),
age: z.string().optional(), // string | undefined
email: z.string().email(), // 验证邮箱格式
role: z.enum(["user", "admin"]),
favorites: z.string().array(),
});
// 导出类型供全局使用
export type User = z.infer<typeof userSchema>;
const getAllUsers = async (): Promise<User[] | null> => {
try {
const data = await usersCollection.get();
return data.docs.map((doc) => userSchema.parse({
...doc.data(),
id: doc.id
}));
} catch (e) {
// 处理错误
}
return null;
};安装命令:
npm i zod
yarn add zod
pnpm add zod文档: Zod 文档
6. next-compose-plugins
简化 Next.js 插件配置的库。
使用场景: 当需要组合多个插件(如 next-translate、@next/bundle-analyzer)时,避免嵌套的 withX 调用。
配置示例:
const withPlugins = require("next-compose-plugins");
const nextTranslate = require("next-translate");
const { withPlausibleProxy } = require("next-plausible");
const withBundleAnalyzer = require("@next/bundle-analyzer");
const nextConfig = {
reactStrictMode: true,
images: {
formats: ['image/avif', 'image/webp'],
domains: [...]
}
};
const plugins = [nextTranslate, withPlausibleProxy()];
// 条件添加分析插件
process.env.APP_ENV === 'ANALYZE' && plugins.push(
withBundleAnalyzer({ enabled: true })
);
module.exports = withPlugins(plugins, nextConfig);安装命令:
npm i next-compose-plugins
yarn add next-compose-plugins
pnpm add next-compose-plugins文档: GitHub - next-compose-plugins
按需安装的库
7. SWR
React Hooks 数据获取库,让数据请求变得异常简单。
核心特性:
- 一行代码处理 loading、error、data 状态
- 支持 SSR、ISR、SSG
- Stale-while-revalidate 策略
- 自动重验证(焦点切换、网络恢复)
- 本地突变实现即时 UI 更新
使用示例:
const fetcher = (...args) => fetch(...args).then((res) => res.json());
const Profile = () => {
const { data, error } = useSWR("/api/user/123", fetcher);
if (error) return <div>failed to load</div>;
if (!data) return <div>loading...</div>;
return <div>hello {data.name}!</div>;
};安装命令:
npm i swr
yarn add swr
pnpm add swr文档: SWR 官网
8. Zustand
轻量级状态管理库,比 Redux 更简单高效。
优势:
- 声明式创建全局状态
- 无需 Provider 包裹
- 支持持久化到 localStorage
- 极少的样板代码
使用示例:
import create from "zustand";
const useStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}));
const BearCounter = () => {
const bears = useStore((state) => state.bears);
return <h1>{bears} around here ...</h1>;
};
const Controls = () => {
const increasePopulation = useStore((state) => state.increasePopulation);
return <button onClick={increasePopulation}>one up</button>;
};使用建议: 优先使用 React Context API,只在状态管理变得复杂时引入 Zustand。
安装命令:
npm i zustand
yarn add zustand
pnpm add zustand文档: GitHub - Zustand
9. Lodash
提供大量实用函数的 JavaScript 工具库。
使用建议:
- 不是所有项目都需要
- 简单功能可自行实现或使用 TypeScript
- 注意正确导入以避免包体积膨胀
替代方案:
- 1 LOC - 单行代码实现常用功能
安装命令:
npm i lodash
yarn add lodash
pnpm add lodash文档: Lodash 官网
10. Day.js
2KB 大小的日期处理库,Moment.js 的现代替代品。
重要提示:
- Moment.js 已进入维护模式,新项目不建议使用
- 简单日期操作可考虑原生 Date 对象
- 参考:JavaScript Date 完全指南
安装命令:
npm i dayjs
yarn add dayjs
pnpm add dayjs文档: Day.js 官网
选择库的建议
1. 控制库的数量
- 每个库都需要维护和更新
- 频繁更新可能导致破坏性变更
- 减少依赖 = 更小的包体积 + 更好的性能
2. 安装前调研
- 搜索是否有更好的替代方案
- 检查库的维护状态和社区活跃度
- 评估对包体积的影响
3. 阅读文档
- 发现库的隐藏功能
- 学习最佳实践
- 了解作者的设计意图
4. 优先使用标准方案
- 优先使用 React 内置功能(如 Context API)
- 只在必要时引入第三方库
- 考虑自己实现简单功能
总结
本文推荐的库组合:
| 类别 | 推荐库 |
|---|---|
| 类型安全 | TypeScript + Zod |
| UI 组件 | Chakra UI |
| 表单处理 | react-hook-form |
| 数据获取 | SWR |
| 状态管理 | Zustand(按需) |
| 插件管理 | next-compose-plugins |
| 依赖更新 | npm-check-updates |
| 日期处理 | Day.js(按需) |
这些库经过生产环境验证,能够显著提升开发效率,同时保持应用的性能和可维护性。
参考链接
- 原文:8 Amazing NextJS Libraries That Make Coding Easier
- 作者:Flavien Bonvin
- 发布日期:2022年7月4日(2024年3月20日更新)