Skip to main content

getStaticPaths

如果一个页面有 动态路由 并使用 getStaticProps,则需要定义静态生成的路径列表。

¥If a page has Dynamic Routes and uses getStaticProps, it needs to define a list of paths to be statically generated.

当你从使用动态路由的页面导出名为 getStaticPaths(静态站点生成)的函数时,Next.js 将静态预渲染 getStaticPaths 指定的所有路径。

¥When you export a function called getStaticPaths (Static Site Generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by getStaticPaths.

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
}
export async function getStaticPaths() {
return {
paths: [
{
params: {
name: 'next.js',
},
}, // See the "paths" section below
],
fallback: true, // false or "blocking"
}
}

export async function getStaticProps() {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
return { props: { repo } }
}

export default function Page({ repo }) {
return repo.stargazers_count
}

getStaticPaths API 参考 涵盖了可与 getStaticPaths 一起使用的所有参数和属性。

¥The getStaticPaths API reference covers all parameters and props that can be used with getStaticPaths.

我什么时候应该使用 getStaticPaths?

¥When should I use getStaticPaths?

如果你静态预渲染使用动态路由的页面并且满足以下条件,则应使用 getStaticPaths

¥You should use getStaticPaths if you’re statically pre-rendering pages that use dynamic routes and:

  • 数据来自无头 CMS

    ¥The data comes from a headless CMS

  • 数据来自数据库

    ¥The data comes from a database

  • 数据来自文件系统

    ¥The data comes from the filesystem

  • 数据可以公开缓存(不特定于用户)

    ¥The data can be publicly cached (not user-specific)

  • 页面必须预渲染(用于 SEO)并且速度非常快 — getStaticProps 生成 HTMLJSON 文件,这两个文件都可以由 CDN 缓存以提高性能

    ¥The page must be pre-rendered (for SEO) and be very fast — getStaticProps generates HTML and JSON files, both of which can be cached by a CDN for performance

getStaticPaths 何时运行

¥When does getStaticPaths run

getStaticPaths 只会在生产环境的构建过程中运行,在运行时不会被调用。你可以验证 getStaticPaths 内编写的代码是否已从客户端打包包 用这个工具 中删除。

¥getStaticPaths will only run during build in production, it will not be called during runtime. You can validate code written inside getStaticPaths is removed from the client-side bundle with this tool.

getStaticProps 如何相对于 getStaticPaths 运行

¥How does getStaticProps run with regards to getStaticPaths

  • 对于构建期间返回的任何 pathsgetStaticPropsnext build 期间运行

    ¥getStaticProps runs during next build for any paths returned during build

  • 使用 fallback: truegetStaticProps 在后台运行

    ¥getStaticProps runs in the background when using fallback: true

  • 使用 fallback: blocking 时,在初始渲染之前调用 getStaticProps

    ¥getStaticProps is called before initial render when using fallback: blocking

在哪里可以使用 getStaticPaths

¥Where can I use getStaticPaths

  • getStaticPaths 必须与 getStaticProps 一起使用

    ¥getStaticPaths must be used with getStaticProps

  • 你不能将 getStaticPathsgetServerSideProps 一起使用

    ¥You cannot use getStaticPaths with getServerSideProps

  • 你可以从也使用 getStaticProps动态路由 导出 getStaticPaths

    ¥You can export getStaticPaths from a Dynamic Route that also uses getStaticProps

  • 你无法从非页面文件(例如 components 文件夹)导出 getStaticPaths

    ¥You cannot export getStaticPaths from non-page file (e.g. your components folder)

  • 你必须将 getStaticPaths 导出为独立函数,而不是页面组件的属性

    ¥You must export getStaticPaths as a standalone function, and not a property of the page component

根据开发中的每个请求运行

¥Runs on every request in development

在开发中 (next dev),每个请求都会调用 getStaticPaths

¥In development (next dev), getStaticPaths will be called on every request.

按需生成路径

¥Generating paths on-demand

getStaticPaths 允许你控制在构建期间生成哪些页面,而不是使用 fallback 按需生成。在构建期间生成更多页面将导致构建速度变慢。

¥getStaticPaths allows you to control which pages are generated during the build instead of on-demand with fallback. Generating more pages during a build will cause slower builds.

你可以通过为 paths 返回空数组来推迟按需生成所有页面。将 Next.js 应用部署到多个环境时,这尤其有用。例如,你可以通过按需生成所有页面进行预览(但不能用于生产构建)来加快构建速度。这对于具有数百/数千个静态页面的网站很有帮助。

¥You can defer generating all pages on-demand by returning an empty array for paths. This can be especially helpful when deploying your Next.js application to multiple environments. For example, you can have faster builds by generating all pages on-demand for previews (but not production builds). This is helpful for sites with hundreds/thousands of static pages.

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 }
}