未验证 提交 a2d83952 编写于 作者: D Daniel Eden 提交者: GitHub

Add with-mdx-remote example (#16613)

This change adds a new example, `with-mdx-remote`, which leverages [`next-mdx-remote`](https://github.com/hashicorp/next-mdx-remote) to use MDX files as content for a dynamic route.

In addition to the basic functionality, the example adds a note about somewhat advanced usage that allows the use of conditionally-loaded custom MDX components.

cc @jescalan
上级 82175978
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local
# vercel
.vercel
# MDX Remote Example
This example shows how a simple blog might be built using the [next-mdx-remote](https://github.com/hashicorp/next-mdx-remote) library, which allows mdx content to be loaded via `getStaticProps` or `getServerSideProps`. The mdx content is loaded from a local folder, but it could be loaded from a database or anywhere else.
The example also showcases [next-remote-watch](https://github.com/hashicorp/next-remote-watch), a library that allows next.js to watch files outside the `pages` folder that are not explicitly imported, which enables the mdx content here to trigger a live reload on change.
Since `next-remote-watch` uses undocumented Next.js APIs, it doesn't replace the default `dev` script for this example. To use it, run `npm run dev:watch` or `yarn dev:watch`.
## Deploy your own
Deploy the example using [Vercel](https://vercel.com):
[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/import/project?template=https://github.com/vercel/next.js/tree/canary/examples/with-mdx-remote)
## How to use
Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npx create-next-app --example with-mdx-remote with-mdx-remote-app
# or
yarn create next-app --example with-mdx-remote with-mdx-remote-app
```
Deploy it to the cloud with [Vercel](https://vercel.com/import?filter=next.js&utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
## Notes
### Conditional custom components
When using `next-mdx-remote`, you can pass custom components to the MDX renderer. However, some pages/MDX files might use components that are used infrequently, or only on a single page. To avoid loading those components on every MDX page, you can use `next/dynamic` to conditionally load them.
For example, here's how you can change `getStaticProps` to conditionally add certain components:
```js
import dynamic from 'next/dynamic'
// ...
export async function getStaticProps() {
const { content, data } = matter(source)
const components = {
...defaultComponents,
SomeHeavyComponent: /<SomeHeavyComponent/.test(content)
? dynamic(() => import('SomeHeavyComponent'))
: null,
}
const mdxSource = await renderToString(content, { components })
}
```
If you do this, you'll also need to check in the page render function which components need to be dynamically loaded. You can pass a list of component names via `getStaticProps` to accomplish this.
import Link from 'next/link'
export default function CustomLink({ as, href, ...otherProps }) {
return (
<>
<Link as={as} href={href}>
<a {...otherProps} />
</Link>
<style jsx>{`
a {
color: tomato;
}
`}</style>
</>
)
}
export default function Layout({ children }) {
return (
<>
<div className="wrapper">{children}</div>
<style jsx>{`
.wrapper {
max-width: 36rem;
margin: 0 auto;
padding: 1.5rem;
}
`}</style>
<style jsx global>{`
* {
margin: 0;
padding: 0;
}
:root {
--site-color: royalblue;
--divider-color: rgba(0, 0, 0, 0.4);
}
html {
font: 100%/1.5 system-ui;
}
a {
color: inherit;
text-decoration-color: var(--divider-color);
text-decoration-thickness: 2px;
}
a:hover {
color: var(--site-color);
text-decoration-color: currentcolor;
}
h1,
p {
margin-bottom: 1.5rem;
}
code {
font-family: 'Menlo';
}
`}</style>
</>
)
}
export default function TestComponent({ name = 'world' }) {
return (
<>
<div>Hello, {name}!</div>
<style jsx>{`
div {
background-color: #111;
border-radius: 0.5em;
color: #fff;
margin-bottom: 1.5em;
padding: 0.5em 0.75em;
}
`}</style>
</>
)
}
{
"name": "with-mdx-remote",
"version": "1.0.0",
"scripts": {
"dev": "next",
"dev:watch": "next-remote-watch ./posts",
"build": "next build",
"start": "next start"
},
"dependencies": {
"gray-matter": "^4.0.2",
"next": "latest",
"next-mdx-remote": "^1.0.0",
"next-remote-watch": "0.2.0",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"license": "MIT"
}
import fs from 'fs'
import matter from 'gray-matter'
import Link from 'next/link'
import path from 'path'
import Layout from '../components/Layout'
import { postFilePaths, POSTS_PATH } from '../utils/mdxUtils'
export default function Index({ posts }) {
return (
<Layout>
<h1>Home Page</h1>
<p>
Click the link below to navigate to a page generated by{' '}
<code>next-mdx-remote</code>.
</p>
<ul>
{posts.map((post) => (
<li key={post.filePath}>
<Link
as={`/posts/${post.filePath.replace(/\.mdx?$/, '')}`}
href={`/posts/[slug]`}
>
<a>{post.data.title}</a>
</Link>
</li>
))}
</ul>
</Layout>
)
}
export function getStaticProps() {
const posts = postFilePaths.map((filePath) => {
const source = fs.readFileSync(path.join(POSTS_PATH, filePath))
const { content, data } = matter(source)
return {
content,
data,
filePath,
}
})
return { props: { posts } }
}
import fs from 'fs'
import matter from 'gray-matter'
import hydrate from 'next-mdx-remote/hydrate'
import renderToString from 'next-mdx-remote/render-to-string'
import dynamic from 'next/dynamic'
import Head from 'next/head'
import Link from 'next/link'
import path from 'path'
import CustomLink from '../../components/CustomLink'
import Layout from '../../components/Layout'
import { postFilePaths, POSTS_PATH } from '../../utils/mdxUtils'
// Custom components/renderers to pass to MDX.
// Since the MDX files aren't loaded by webpack, they have no knowledge of how
// to handle import statements. Instead, you must include components in scope
// here.
const components = {
a: CustomLink,
// It also works with dynamically-imported components, which is especially
// useful for conditionally loading components for certain routes.
// See the notes in README.md for more details.
TestComponent: dynamic(() => import('../../components/TestComponent')),
Head,
}
export default function PostPage({ source, frontMatter }) {
const content = hydrate(source, { components })
return (
<Layout>
<header>
<nav>
<Link href="/">
<a>👈 Go back home</a>
</Link>
</nav>
</header>
<div className="post-header">
<h1>{frontMatter.title}</h1>
{frontMatter.description && (
<p className="description">{frontMatter.description}</p>
)}
</div>
<main>{content}</main>
<style jsx>{`
.post-header h1 {
margin-bottom: 0;
}
.post-header {
margin-bottom: 2rem;
}
.description {
opacity: 0.6;
}
`}</style>
</Layout>
)
}
export const getStaticProps = async ({ params }) => {
const postFilePath = path.join(POSTS_PATH, `${params.slug}.mdx`)
const source = fs.readFileSync(postFilePath)
const { content, data } = matter(source)
const mdxSource = await renderToString(content, {
components,
// Optionally pass remark/rehype plugins
mdxOptions: {
remarkPlugins: [],
rehypePlugins: [],
},
scope: data,
})
return {
props: {
source: mdxSource,
frontMatter: data,
},
}
}
export const getStaticPaths = async () => {
const paths = postFilePaths
// Remove file extensions for page paths
.map((path) => path.replace(/\.mdx?$/, ''))
// Map the path into the static paths object required by Next.js
.map((slug) => ({ params: { slug } }))
return {
paths,
fallback: false,
}
}
---
title: Example Post
description: This frontmatter description will appear below the title
---
This is an example post, with a [link](https://nextjs.org) and a React component:
<TestComponent name="next-mdx-remote" />
The title and description are pulled from the MDX file and processed using `gray-matter`. Additionally, links are rendered using a custom component passed to `next-mdx-remote`.
Go back [home](/).
---
title: Hello World
---
This is an example post. There's another one [here](/posts/example-post).
import fs from 'fs'
import path from 'path'
// POSTS_PATH is useful when you want to get the path to a specific file
export const POSTS_PATH = path.join(process.cwd(), 'posts')
// postFilePaths is the list of all mdx files inside the POSTS_PATH directory
export const postFilePaths = fs
.readdirSync(POSTS_PATH)
// Only include md(x) files
.filter((path) => /\.mdx?$/.test(path))
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册