生产环境
¥Production
在将 Next.js 应用投入生产之前,你应该考虑实现一些优化和模式,以获得最佳的用户体验、性能和安全性。
¥Before taking your Next.js application to production, there are some optimizations and patterns you should consider implementing for the best user experience, performance, and security.
本页面提供了在使用 构建你的应用、在投入生产之前 以及 自动 Next.js 优化 时可以作为参考的最佳实践。
¥This page provides best practices that you can use as a reference when building your application and before going to production, as well as the automatic Next.js optimizations you should be aware of.
自动优化
¥Automatic optimizations
这些 Next.js 优化默认启用,无需配置:
¥These Next.js optimizations are enabled by default and require no configuration:
代码分割:Next.js 会自动按页面对应用代码进行代码拆分。这意味着导航时仅加载当前页面所需的代码。你还可以在适当的情况下考虑使用 延迟加载 第三方库。
¥Code-splitting: Next.js automatically code-splits your application code by pages. This means only the code needed for the current page is loaded on navigation. You may also consider lazy loading third-party libraries, where appropriate.
预请求:当指向新路由的链接进入用户的视口时,Next.js 会在后台预取该路由。这使得导航到新路由几乎是即时的。你可以在适当的情况下选择退出预取。
¥Prefetching: When a link to a new route enters the user's viewport, Next.js prefetches the route in background. This makes navigation to new routes almost instant. You can opt out of prefetching, where appropriate.
自动静态优化:如果页面没有阻塞数据需求,Next.js 会自动将页面确定为静态页面(可以预渲染)。优化后的页面可以缓存,并从多个 CDN 位置提供给终端用户。你可以在适当的情况下选择启用 服务端渲染。
¥Automatic Static Optimization: Next.js automatically determines that a page is static (can be pre-rendered) if it has no blocking data requirements. Optimized pages can be cached, and served to the end-user from multiple CDN locations. You may opt into Server-side Rendering, where appropriate.
这些默认值旨在提高应用的性能,并降低每个网络请求传输的成本和数据量。
¥These defaults aim to improve your application's performance, and reduce the cost and amount of data transferred on each network request.
开发期间
¥During development
在构建应用时,我们建议使用以下功能以确保最佳性能和用户体验:
¥While building your application, we recommend using the following features to ensure the best performance and user experience:
路由和渲染
¥Routing and rendering
<Link>
组件:使用<Link>
组件进行客户端导航和预加载。¥
<Link>
component: Use the<Link>
component for client-side navigation and prefetching.¥Custom Errors: Gracefully handle 500 and 404 errors
数据获取和缓存
¥Data fetching and caching
API 路由:使用路由处理程序访问后端资源,防止敏感信息泄露给客户端。
¥API Routes: Use Route Handlers to access your backend resources, and prevent sensitive secrets from being exposed to the client.
数据缓存:验证你的数据请求是否正在缓存,并在适当的情况下选择缓存。确保不使用
getStaticProps
的请求在适当的位置缓存。¥Data Caching: Verify whether your data requests are being cached or not, and opt into caching, where appropriate. Ensure requests that don't use
getStaticProps
are cached where appropriate.增量静态再生:使用增量静态再生功能在静态页面构建完成后进行更新,无需重建整个网站。
¥Incremental Static Regeneration: Use Incremental Static Regeneration to update static pages after they've been built, without rebuilding your entire site.
静态图片:使用
public
目录自动缓存应用的静态资源,例如 图片。¥Static Images: Use the
public
directory to automatically cache your application's static assets, e.g. images.
用户界面和可访问性
¥UI and accessibility
字体模块:使用字体模块优化字体,该模块自动将你的字体文件与其他静态资源一起托管,删除外部网络请求,并减少 布局转变。
¥Font Module: Optimize fonts by using the Font Module, which automatically hosts your font files with other static assets, removes external network requests, and reduces layout shift.
<Image>
组件:使用图片组件优化图片,该组件会自动优化图片、防止布局偏移并以 WebP 等现代格式提供图片。¥
<Image>
Component: Optimize images by using the Image Component, which automatically optimizes images, prevents layout shift, and serves them in modern formats like WebP.<Script>
组件:使用脚本组件优化第三方脚本,该组件会自动延迟脚本并防止它们阻塞主线程。¥
<Script>
Component: Optimize third-party scripts by using the Script Component, which automatically defers scripts and prevents them from blocking the main thread.ESLint:使用内置的
eslint-plugin-jsx-a11y
插件尽早发现可访问性问题。¥ESLint: Use the built-in
eslint-plugin-jsx-a11y
plugin to catch accessibility issues early.
安全
¥Security
环境变量:确保你的
.env.*
文件已添加到.gitignore
,并且只有公共变量的前缀为NEXT_PUBLIC_
。¥Environment Variables: Ensure your
.env.*
files are added to.gitignore
and only public variables are prefixed withNEXT_PUBLIC_
.内容安全政策:考虑添加内容安全策略来保护你的应用免受各种安全威胁,例如跨站点脚本、点击劫持和其他代码注入攻击。
¥Content Security Policy: Consider adding a Content Security Policy to protect your application against various security threats such as cross-site scripting, clickjacking, and other code injection attacks.
元数据和搜索引擎优化
¥Metadata and SEO
<Head>
组件:使用next/head
组件添加页面标题、描述等。¥
<Head>
Component: Use thenext/head
component to add page titles, descriptions, and more.
类型安全
¥Type safety
TypeScript 和 TS 插件:使用 TypeScript 和 TypeScript 插件可以获得更好的类型安全性,并帮助你尽早发现错误。
¥TypeScript and TS Plugin: Use TypeScript and the TypeScript plugin for better type-safety, and to help you catch errors early.
投入生产之前
¥Before going to production
在投入生产之前,你可以运行 next build
在本地构建应用并捕获任何构建错误,然后运行 next start
来测量应用在类似生产环境中的性能。
¥Before going to production, you can run next build
to build your application locally and catch any build errors, then run next start
to measure the performance of your application in a production-like environment.
核心网络生命力
¥Core Web Vitals
灯塔:以隐身方式运行 Lighthouse,以便更好地了解用户将如何体验你的网站,并确定需要改进的字段。这是一个模拟测试,应该与查看现场数据(例如 Core Web Vitals)结合起来。
¥Lighthouse: Run lighthouse in incognito to gain a better understanding of how your users will experience your site, and to identify areas for improvement. This is a simulated test and should be paired with looking at field data (such as Core Web Vitals).
分析打包
¥Analyzing bundles
使用 @next/bundle-analyzer
插件 分析 JavaScript 包的大小并识别可能影响应用性能的大型模块和依赖。
¥Use the @next/bundle-analyzer
plugin to analyze the size of your JavaScript bundles and identify large modules and dependencies that might be impacting your application's performance.
此外,以下工具可以帮助你了解向应用添加新依赖的影响:
¥Additionally, the following tools can help you understand the impact of adding new dependencies to your application: