Skip to content

Commit 72b4868

Browse files
committed
initial commit
0 parents  commit 72b4868

8 files changed

+2132
-0
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.DS_Store
2+
node_modules

.prettierrc

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"semi": false,
3+
"singleQuote": true
4+
}

README.md

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Next MDX Remote
2+
3+
A set of light utilities allowing mdx to be loaded within `getStaticProps` or `getServerSideProps` and hydrated correctly on the client.
4+
5+
### Background & Theory
6+
7+
If you are using mdx within a nextjs app, you are probably using the webpack loader. This means that you have your mdx files locally and are probably using [next-mdx-enhanced](https://github.com/hashicorp/next-mdx-enhanced) in order to be able to render your mdx files into layouts and import their front matter to create index pages. This workflow is fine, but introduces a few limitations that we aim to remove with `next-mdx-remote`:
8+
9+
- The file content must be local. You cannot store mdx files in another repo, a database, etc. For a large enough operation, there will end up being a split between those authoring content and those working on presentation of the content. Overlapping these two concerns in the same repo makes a more difficult workflow for everyone.
10+
- You are bound to filesystem-based routing. Your pages are generated with urls according to their locations. Or maybe you remap them using `exportPathMap`, which creates confusion for authors. Regardless, moving pages around in any way breaks things -- either the page's url or your `exportPathMap` configuration.
11+
- You will end up running into performance issues. Webpack is a javascript bundler, forcing it to load hundreds/thousands of pages of text content will blow out your memory requirements - webpack stores each page as a distinct object with a large amount of metadata. One of our implementations with a couple hundred pages hit more than 8gb of memory required to compile the site. Builds took more than 25 minutes.
12+
- You will be limited in the ways you are able to structure relational data. Organizing content into dynamic, related categories is difficult when your entire data structure is front matter parsed into javascript objects and held in memory.
13+
14+
So, `next-mdx-remote` changes the entire pattern so that you load your mdx content not through an import, but rather through `getStaticProps` or `getServerProps` -- you know, the same way you would load any other data. The library provides the tools to serialize and hydrate the mdx content in a manner that is performant. This removed all of the limitations listed above, and does so at a significantly lower cost -- `next-mdx-enhanced` is a very heavy library with a lot of custom logic and [some annoying limitations](https://github.com/hashicorp/next-mdx-enhanced/issues/17). Early testing has shown build times reduced by 50% or more.
15+
16+
### Installation
17+
18+
```
19+
npm i next-mdx-remote
20+
```
21+
22+
### Usage
23+
24+
This library exposes two functions, `renderToString` and `hydrate`, much like `react-dom`. These two are purposefully isolated into their own files -- `renderToString` is intended to be run **server-side**, so within `getStaticProps`, which runs on the server/at build time. `hydrate` on the other hand is intended to be run on the client side, in the browser.
25+
26+
```jsx
27+
import renderToString from 'next-mdx-enhanced/render-to-string'
28+
import hydrate from 'next-mdx-enhanced/hydrate'
29+
import Test from '../components/test'
30+
31+
const components = { Test }
32+
33+
export default function TestPage({ mdxSource }) {
34+
const content = hydrate(mdxSource, components)
35+
return <div className="wrapper">{content}</div>
36+
}
37+
38+
export async function getStaticProps() {
39+
// mdx text - can be from a local file, database, anywhere
40+
const source = 'Some **mdx** text, with a component <Test />'
41+
const mdxSource = await renderToString(source, components)
42+
return { props: { mdxSource } }
43+
}
44+
```
45+
46+
While it may seem strange to see these two in the same file, this is one of the cool things about next.js -- `getStaticProps` and `TestPage`, while appearing in the same file, run in two different places. Ultimately your browser bundle will not include `getStaticProps` at all, or any of the functions only it uses, so `renderToString` will be removed from the browser bundle entirely.
47+
48+
Let's break down each function:
49+
50+
- `renderToString(source: string, components: object)` - This function consumes a string of mdx along with any components it utilizes in the format `{ ComponentName: ActualComponent }`. The function returns an object that is intended to be passed into `hydrate` directly.
51+
- `hydrate(source: object, components: object)` - This function consumes the output of `renderToString` as well as the same components argument as `renderToString`. Its result can be rendered directly into your component. This function will initially render static content, and hydrate it when the browser isn't busy with higher priority tasks.
52+
53+
### Frontmatter & Custom Processing
54+
55+
Markdown in general is often paired with frontmatter, and normally this means adding some extra custom processing to the way markdown is handled. Luckily, this can be done entirely independently of `next-mdx-remote`, along with any extra custom processing necessary. Let's walk through an example of how we could process frontmatter out of our mdx source.
56+
57+
```jsx
58+
import renderToString from 'next-mdx-enhanced/render-to-string'
59+
import hydrate from 'next-mdx-enhanced/hydrate'
60+
import Test from '../components/test'
61+
import matter from 'gray-matter'
62+
63+
const components = { Test }
64+
65+
export default function TestPage({ mdxSource, frontMatter }) {
66+
const content = hydrate(mdxSource, components)
67+
return (
68+
<div className="wrapper">
69+
<h1>{frontMatter.title}</h1>
70+
{content}
71+
</div>
72+
)
73+
}
74+
75+
export async function getStaticProps() {
76+
// mdx text - can be from a local file, database, anywhere
77+
const source = 'Some **mdx** text, with a component <Test />'
78+
const { content, data } = matter(content)
79+
const mdxSource = await renderToString(content, components)
80+
return { props: { mdxSource, frontMatter: data } }
81+
}
82+
```
83+
84+
Nice and easy - since we get the content as a string originally and have full control, we can run any extra custom processing needed before passing it into `renderToString`, and easily append extra data to the return value from `getStaticProps` without issue.
85+
86+
### Caveats
87+
88+
There's only one caveat here, which is that `import` cannot be used **inside** an mdx file. If you need to use components in your mdx files, they should be provided through the second argument to the `hydrate` and `renderToString` functions.
89+
90+
Hopefully this makes sense, since in order to work, imports must be relative to a file path, and this library allows content to be loaded from anywhere, rather than only loading local content from a set file path.

babel-plugin-mdx-browser.js

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
module.exports = function BabelPluginMdxBrowser() {
2+
return {
3+
visitor: {
4+
// remove all imports, we will add these to scope manually
5+
ImportDeclaration(path) {
6+
path.remove()
7+
},
8+
// the `makeShortcode` template is nice for error handling but we
9+
// don't need it here as we are manually injecting dependencies
10+
VariableDeclaration(path) {
11+
// this removes the `makeShortcode` function
12+
if (path.node.declarations[0].id.name === 'makeShortcode') {
13+
path.remove()
14+
}
15+
16+
// this removes any variable that is set using the `makeShortcode` function
17+
if (
18+
path.node &&
19+
path.node.declarations &&
20+
path.node.declarations[0] &&
21+
path.node.declarations[0].init &&
22+
path.node.declarations[0].init.callee &&
23+
path.node.declarations[0].init.callee.name === 'makeShortcode'
24+
) {
25+
path.remove()
26+
}
27+
},
28+
// remove the default export
29+
ExportDefaultDeclaration(path) {
30+
path.replaceWith(path.node.declaration)
31+
},
32+
},
33+
}
34+
}

hydrate.js

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import React, { useMemo, useState } from 'react'
2+
import { mdx } from '@mdx-js/react'
3+
4+
export default function hydrate({ source, renderedOutput }, components) {
5+
const [hydrated, setHydrated] = useState(false)
6+
7+
// our default result is the server-rendered output
8+
// we get this in front of users as quickly as possible
9+
const [result, setResult] = useState(
10+
<span dangerouslySetInnerHTML={{ __html: renderedOutput }} />
11+
)
12+
13+
// if we're on the client side and have not yet hydrated, we hydrate
14+
// the mdx content inside requestIdleCallback, since we can be fairly
15+
// confident that markdown-embedded components are not a high priority
16+
// to get to interactive compared to... anything else on the page.
17+
//
18+
// once the hydration is complete, we update the state/memo value and
19+
// react re-renders for us
20+
typeof window !== 'undefined' &&
21+
!hydrated &&
22+
window.requestIdleCallback(() => {
23+
// first we set up the scope which has to include the mdx custom
24+
// create element function as well as any components we're using
25+
const scope = { mdx, ...components }
26+
const keys = Object.keys(scope)
27+
const values = Object.values(scope)
28+
29+
// now we eval the source code using a function constructor
30+
// in order for this to work we need to have React, the mdx createElement,
31+
// and all our components in scope for the function, which is the case here
32+
// we pass the names (via keys) in as the function's args, and execute the
33+
// function with the actual values.
34+
const hydratedFn = new Function(
35+
'React',
36+
...keys,
37+
`${source}
38+
return React.createElement(MDXContent, {});`
39+
)(React, ...values)
40+
41+
// finally, we flip the hydrated status so this doesn't run again, and set
42+
// the output as the new result so that
43+
setHydrated(true)
44+
setResult(hydratedFn)
45+
})
46+
47+
return useMemo(() => result, [source, result])
48+
}

0 commit comments

Comments
 (0)