Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add with-mdx-remote example #16613

Merged
merged 17 commits into from
Aug 29, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions examples/with-mdx-remote/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# 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
71 changes: 71 additions & 0 deletions examples/with-mdx-remote/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Example app with MDX

This example shows using [next-mdx-remote](https://github.com/hashicorp/next-mdx-remote) to import MDX file content to statically-generated pages.

## 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

### Using `create-next-app`

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 with-mdx-remote-app
# or
yarn create next-app --example with-mdx with-mdx-remote-app
```

### Download manually

Download the example:

```bash
curl https://codeload.github.com/vercel/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-mdx-remote
cd with-mdx-remote
```

Install it and run:

```bash
npm install
npm run dev
# or
yarn
yarn dev
```

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 `getInitialProps` to conditionally add certain components:

```js
import dynamic from "next/dynamic"
...

async function getInitialProps() {
const { content, data } = matter(source)

const components = {
...defaultComponents,
SomeHeavyComponent: /<SomeHeavyComponent/.test(content) ? dynamic(() => import("SomeHeavyComponent")) : null,
}

const mdxSource = await renderToString(content, {
components,
...otherOptions,
})
}
```

If you do this, you'll need to also check in the page render function which components need to be dynamically loaded. You can pass a list of components names via `getInitialProps` to accomplish this.
daneden marked this conversation as resolved.
Show resolved Hide resolved
16 changes: 16 additions & 0 deletions examples/with-mdx-remote/components/CustomLink.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Link from 'next/link'

export default function CustomLink({ href, ...otherProps }) {
return (
<>
<Link href={href}>
<a {...otherProps} />
</Link>
<style jsx>{`
a {
color: tomato;
}
`}</style>
</>
)
}
5 changes: 5 additions & 0 deletions examples/with-mdx-remote/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
env: {
mdxPath: 'posts',
},
}
18 changes: 18 additions & 0 deletions examples/with-mdx-remote/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"name": "with-mdx-remote",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"dependencies": {
"gray-matter": "^4.0.2",
"next": "latest",
"next-mdx-remote": "^1.0.0",
"react": "^16.8.6",
"react-dom": "^16.8.6"
},
"devDependencies": {},
daneden marked this conversation as resolved.
Show resolved Hide resolved
"license": "ISC"
}
41 changes: 41 additions & 0 deletions examples/with-mdx-remote/pages/index.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import fs from 'fs'
import matter from 'gray-matter'
import Link from 'next/link'
import path from 'path'
import { postFilePaths, POSTS_PATH } from '../utils/mdxUtils'

export default function Index({ posts }) {
return (
<>
<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 href={`/posts/${post.filePath.replace(/\.mdx?$/, '')}`}>
daneden marked this conversation as resolved.
Show resolved Hide resolved
<a>{post.data.title}</a>
</Link>
</li>
))}
</ul>
</>
)
}

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 } }
}
72 changes: 72 additions & 0 deletions examples/with-mdx-remote/pages/posts/[slug].jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
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 Link from 'next/link'
import path from 'path'
import CustomLink from '../../components/CustomLink'
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,
}

export default function PostPage({ source, frontMatter }) {
const content = hydrate(source, { components })
return (
<>
<header>
<nav>
<Link href="/">
<a>👈 Go back home</a>
</Link>
</nav>
</header>
<div className="wrapper">
<h1>{frontMatter.title}</h1>
{content}
</div>
</>
)
}

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,
}
}
7 changes: 7 additions & 0 deletions examples/with-mdx-remote/posts/example-post.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
title: Example Post
---

This is an example post, with a [link](https://nextjs.org).

Go back [home](/).
5 changes: 5 additions & 0 deletions examples/with-mdx-remote/posts/hello-world.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
title: Hello World
---

This is an example post. There's another one [here](/posts/example-post).
11 changes: 11 additions & 0 deletions examples/with-mdx-remote/utils/mdxUtils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
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(), process.env.mdxPath)
daneden marked this conversation as resolved.
Show resolved Hide resolved

// 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))