getStaticPaths
如果页面具有动态路由并使用 getStaticProps
,则需要定义要静态生成的路径列表。
当您从使用动态路由的页面导出名为 getStaticPaths
(静态站点生成) 的函数时,Next.js 将静态预渲染 getStaticPaths
指定的所有路径。
pages/repo/[name].tsx
import type {
InferGetStaticPropsType,
GetStaticProps,
GetStaticPaths,
} from 'next'
type Repo = {
name: string
stargazers_count: number
}
export const getStaticPaths = (async () => {
return {
paths: [
{
params: {
name: 'next.js',
},
}, // See the "paths" section below
],
fallback: true, // false or "blocking"
}
}) satisfies GetStaticPaths
export const getStaticProps = (async (context) => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}) satisfies GetStaticProps<{
repo: Repo
}>
export default function Page({
repo,
}: InferGetStaticPropsType<typeof getStaticProps>) {
return repo.stargazers_count
}
getStaticPaths
API 参考涵盖了可与 getStaticPaths
一起使用的所有参数和属性。
我应该何时使用 getStaticPaths?
如果您要静态预渲染使用动态路由的页面,并且满足以下条件,则应使用 getStaticPaths
- 数据来自无头 CMS
- 数据来自数据库
- 数据来自文件系统
- 数据可以公开缓存(非用户特定)
- 页面必须预渲染(为了 SEO)并且速度非常快——
getStaticProps
生成HTML
和JSON
文件,这两者都可以被 CDN 缓存以提高性能
getStaticPaths 何时运行
getStaticPaths
只会在生产构建期间运行,不会在运行时调用。您可以使用此工具验证在 getStaticPaths
内部编写的代码是否已从客户端包中删除。
getStaticProps 如何相对于 getStaticPaths 运行
getStaticProps
在next build
期间为构建期间返回的任何paths
运行- 使用
fallback: true
时,getStaticProps
在后台运行 - 使用
fallback: blocking
时,getStaticProps
在初始渲染之前调用
我在哪里可以使用 getStaticPaths
getStaticPaths
必须 与getStaticProps
一起使用- 您不能将
getStaticPaths
与getServerSideProps
一起使用 - 您可以从也使用
getStaticProps
的动态路由导出getStaticPaths
- 您不能从非页面文件(例如您的
components
文件夹)导出getStaticPaths
- 您必须将
getStaticPaths
导出为独立函数,而不是页面组件的属性
在开发中每次请求时运行
在开发环境 (next dev
) 中,getStaticPaths
将在每次请求时调用。
按需生成路径
getStaticPaths
允许您控制在构建期间生成的页面,而不是使用fallback
按需生成。在构建期间生成更多页面将导致构建速度变慢。
您可以通过为 paths
返回一个空数组来延迟按需生成所有页面。当您将 Next.js 应用程序部署到多个环境时,这尤其有用。例如,您可以通过按需生成所有预览页面(但不是生产构建)来加快构建速度。这对于具有数百/数千个静态页面的站点很有帮助。
pages/posts/[id].js
export async function getStaticPaths() {
// When this is true (in preview environments) don't
// prerender any static pages
// (faster builds, but slower initial page load)
if (process.env.SKIP_BUILD_STATIC_GENERATION) {
return {
paths: [],
fallback: 'blocking',
}
}
// Call an external API endpoint to get posts
const res = await fetch('https://.../posts')
const posts = await res.json()
// Get the paths we want to prerender based on posts
// In production environments, prerender all pages
// (slower builds, but faster initial page load)
const paths = posts.map((post) => ({
params: { id: post.id },
}))
// { fallback: false } means other routes should 404
return { paths, fallback: false }
}
这有帮助吗?