乐闻世界logo
搜索文章和话题

NextJS : How to get static assets from within getStaticProps

1个答案

1

When developing a website or application with Next.js, you may need to fetch static assets during the build, such as retrieving data from the file system or external APIs to pre-render pages. getStaticProps is an asynchronous function that enables you to fetch the required data during the build and pass it as props to your page.

Steps

  1. Create a getStaticProps function: In your page component file, export an asynchronous function named getStaticProps. This function executes during the build.

  2. Fetch data: Within getStaticProps, you can read local files, query databases, or call external APIs to retrieve your static data.

  3. Return the data: Once you fetch the data, wrap it in an object and return it as props.

Example Code

Suppose we have a blog website, and we aim to fetch the static content of blog posts from a local Markdown file:

jsx
// pages/blog/[slug].js import fs from 'fs'; import path from 'path'; import matter from 'gray-matter'; import React from 'react'; const BlogPost = ({ content, title }) => { return ( <article> <h1>{title}</h1> <div dangerouslySetInnerHTML={{ __html: content }} /> </article> ); }; export async function getStaticPaths() { const files = fs.readdirSync(path.join('posts')); const paths = files.map((filename) => ({ params: { slug: filename.replace('.md', ''), }, })); return { paths, fallback: false, }; } export async function getStaticProps({ params }) { // Retrieve the path of the Markdown file const markdownWithMetadata = fs.readFileSync( path.join('posts', params.slug + '.md'), 'utf-8' ); // Parse the metadata section of the Markdown file using gray-matter const { data, content } = matter(markdownWithMetadata); // Convert the Markdown content to an HTML string (you can use remark or other Markdown-to-HTML libraries here) const htmlContent = someMarkdownToHtmlFunction(content); // Return the fetched data return { props: { title: data.title, content: htmlContent, }, }; } export default BlogPost;

In the above example, we first access the Markdown file using the fs and path modules. Then, we parse the file content and metadata using the gray-matter library. Finally, we convert the Markdown content to an HTML string and pass the title and content as props to the page component.

This page is generated during the build, and the content of each blog post is retrieved and converted during the build, then cached as static assets. When a user requests a specific blog post page in the browser, Next.js serves the static page, achieving fast loading and excellent performance.

2024年6月29日 12:07 回复

你的答案