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 }
}这有帮助吗?