Skip to content

Commit b46851a

Browse files
authored
Merge pull request #71 from timlrx/fix/next-react-mdx-runtime
import react runtime in getMDXComponent
2 parents 37c800c + 7591b00 commit b46851a

File tree

4 files changed

+542
-21
lines changed

4 files changed

+542
-21
lines changed

packages/@contentlayer/core/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@
4040
"comment-json": "^4.2.3",
4141
"esbuild": ">=0.17",
4242
"gray-matter": "^4.0.3",
43-
"mdx-bundler": "^10.0.2",
43+
"mdx-bundler": "^10.1.1",
4444
"rehype-stringify": "^10.0.0",
4545
"remark-frontmatter": "^5.0.0",
4646
"remark-parse": "^11.0.0",

packages/next-contentlayer/src/hooks/useMDXComponent.ts

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,32 @@
1-
import { getMDXComponent } from '@contentlayer2/core/client'
2-
// NOTE use ESM/CommonJS compat import here until resolved: https://github.com/facebook/react/issues/11503
3-
import React from 'react'
1+
import { getMDXComponent as getMDXComponentOriginal } from '@contentlayer2/core/client'
2+
import * as React from 'react'
3+
import * as _jsx_dev_runtime from 'react/jsx-dev-runtime'
4+
import * as _jsx_runtime from 'react/jsx-runtime'
5+
import * as ReactDOM from 'react-dom'
46

5-
export { getMDXComponent }
7+
// Pass in the React module into the evaluated code instead of having the evaluated code import React
8+
// See https://github.com/timlrx/contentlayer2/issues/66
9+
const defaultRuntime = {
10+
React,
11+
ReactDOM,
12+
_jsx_runtime: process.env.NODE_ENV === 'production' ? _jsx_runtime : _jsx_dev_runtime,
13+
}
14+
15+
/**
16+
* Get an MDX component from compiled MDX code
17+
*
18+
* @param code - The string of code you got from bundleMDX
19+
* @param globals - Any variables your MDX needs to have accessible when it runs
20+
* @returns A React component that renders the MDX content
21+
*/
22+
export const getMDXComponent = (code: string, globals: Record<string, unknown> = {}) => {
23+
const options = {
24+
...defaultRuntime,
25+
...globals,
26+
}
27+
28+
return getMDXComponentOriginal(code, options)
29+
}
630

731
export const useMDXComponent = (code: string, globals: Record<string, unknown> = {}) => {
832
return React.useMemo(() => getMDXComponent(code, globals), [code, globals])

0 commit comments

Comments
 (0)