静态生成
使用 Next.js,你可以使用 静态生成 (SSG) 来预渲染页面。您的页面将在构建时生成,并静态提供给访问者。另外还可以通过 CDN 缓存,以最大限度地提高性能。
Nextra 也支持这一特性。下面是一个示例:
Nextra has 12861 stars on GitHub!
上面的数字是在构建时通过 getStaticProps
生成的。启用 Incremental Static Regeneration 后,它将一直保持最新状态。
下面是上述示例的 MDX 代码:
import { useSSG } from 'nextra/ssg'export const getStaticProps = ({ params }) => { return fetch(`https://api.github.com/repos/shuding/nextra`) .then((res) => res.json()) .then((repo) => ({ props: { // We add an `ssg` field to the page props, // which will be provided to the Nextra `useSSG` hook. ssg: { stars: repo.stargazers_count, }, }, // The page will be considered as stale and regenerated every 60 seconds. revalidate: 60, }))}export const Stars = () => { // Get the data from SSG, and render it as a component. const { stars } = useSSG() return <strong>{stars}</strong>}Nextra has <Stars /> stars on GitHub!