-
In MDX 2, If you import an MDX document directly, you can work around this by importing the values you need (as described in the MDX 2 migration guide). But in other scenarios (for example, using MDX documents with the Next.js filesystem router), the MDX document is never directly imported by the user. I haven't yet figured out how to work around this—if I don't explicitly import the MDX document, I can no longer access its exports in the layout. I tried using a I'm still trying to figure out other ways around this issue, but how is everybody else doing it? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Is |
Beta Was this translation helpful? Give feedback.
-
I think I've stumbled upon an interesting work around. MDX documents can export a To make this smoother, I created a function to modify the AST and automatically add a
Here's my first attempt. 🚨 Not fully tested; just thrown together as a proof of concept: import { parse } from 'acorn'
/**
* AST transformer adds `getStaticProps` to the tree based on provided mapping.
*/
function createNextStaticProps(map) {
return function transformer(tree) {
tree.children.push({
type: 'mdxjsEsm',
data: {
estree: parse(
`
export const getStaticProps = async () => {
return {
props: ${map},
}
}`,
{
sourceType: 'module',
},
),
},
})
}
} Include the transformer in MDX options: import withToc from '@stefanprobst/rehype-extract-toc'
import withTocExport from '@stefanprobst/rehype-extract-toc/mdx'
// ...
{
rehypePlugins: [
withToc,
withTocExport,
[
createNextStaticProps,
`{
meta,
tableOfContents,
}`,
],
],
} Now, the exports export const meta = {
title: 'JSON Feed Types',
description: `I've been working on adding JSON Feed to my blog, but I was surprised to discover that nobody has published JSON Feed TypeScript types yet. So I made some.`,
date: '2021-10-01',
tags: ['JSON Feed', 'TypeScript'],
}
I've been working on adding [JSON Feed](https://www.jsonfeed.org) to my blog. |
Beta Was this translation helpful? Give feedback.
I think I've stumbled upon an interesting work around. MDX documents can export a
getStaticProps
function just like any other Next.js page. Page props can be used in a similar way tolayoutProps
in MDX 1. We can add agetStaticProps
function to the MDX document that returns values we want to expose as Next.js page props.To make this smoother, I created a function to modify the AST and automatically add a
getStaticProps
function based on a mapping provided by the user. This means:pageProps
prop passed to_app.tsx
).Here's my first attempt. 🚨 Not fully tested; jus…