什么是 Next.js
Next.js 是一个基于 React 的全栈框架,最吸引人的地方是它开箱即用的预渲染能力。
两种预渲染方式
- SSG(静态生成):构建时生成 HTML,
getStaticProps - SSR(服务端渲染):每次请求时生成,
getServerSideProps
getStaticProps 示例
export const getStaticProps: GetStaticProps = async () => {
const posts = getSortedPostsData();
return { props: { posts } };
};
getStaticPaths 的作用
动态路由需要提前告诉 Next.js 要生成哪些页面:
export const getStaticPaths: GetStaticPaths = async () => {
const paths = getAllPostIds();
return { paths, fallback: false };
};
掌握这两个函数,静态博客基本就够用了。