未验证 提交 a7bd2db9 编写于 作者: R Ronie 提交者: GitHub

Example: update netlify-cms to use SSG (#12072)

上级 945c1fac
......@@ -41,5 +41,4 @@ Sites take its content from markdown files in `/content`. Two of pages (`home` a
Blog component loads all posts (during build!) and lists them out [How to load multiple md files](https://medium.com/@shawnstern/importing-multiple-markdown-files-into-a-react-component-with-webpack-7548559fce6f)
Posts are separate static sites thanks to dynamically created export map. I took inspiration on how to do it from
[here](https://medium.com/@joranquinten/for-my-own-website-i-used-next-js-725678e65b09)
Updated to take advantange of the new `getStaticPaths` and `getStaticProps` data-fetching functions.
const fs = require('fs')
const blogPostsFolder = './content/blogPosts'
const getPathsForPosts = () =>
fs.readdirSync(blogPostsFolder).reduce((acc, blogName) => {
const trimmedName = blogName.substring(0, blogName.length - 3)
return Object.assign(acc, {
[`/blog/post/${trimmedName}`]: {
page: '/blog/post/[slug]',
query: {
slug: trimmedName,
},
},
})
}, {})
module.exports = {
webpack: configuration => {
configuration.module.rules.push({
......@@ -22,10 +6,4 @@ module.exports = {
})
return configuration
},
async exportPathMap(defaultPathMap) {
return {
...defaultPathMap,
...getPathsForPosts(),
}
},
}
......@@ -40,9 +40,14 @@ const Blog = ({ postsList }) => (
</Layout>
)
Blog.getInitialProps = async () => {
export async function getStaticProps() {
const postsList = await importBlogPosts()
return { postsList }
return {
props: {
postsList,
}, // will be passed to the page component as props
}
}
export default Blog
import fs from 'fs'
import path from 'path'
import Layout from '../../../components/layout'
const Post = ({ blogpost }) => {
if (!blogpost) return <div>not found</div>
const { html, attributes } = blogpost.default
const { html, attributes } = blogpost
return (
<Layout>
......@@ -24,12 +26,34 @@ const Post = ({ blogpost }) => {
)
}
Post.getInitialProps = async ({ query }) => {
const { slug } = query
export async function getStaticPaths() {
const paths = fs
.readdirSync(path.join(process.cwd(), 'content/blogPosts'))
.map(blogName => {
const trimmedName = blogName.substring(0, blogName.length - 3)
return {
params: { slug: trimmedName },
}
})
return {
paths,
fallback: false, // constrols wheter not predefined paths should be processed on demand, check for more info: https://nextjs.org/docs/basic-features/data-fetching#the-fallback-key-required
}
}
export async function getStaticProps({ params }) {
const { slug } = params
const blogpost = await import(`../../../content/blogPosts/${slug}.md`).catch(
() => null
)
return { blogpost }
return {
props: {
blogpost: blogpost.default,
},
}
}
export default Post
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册