Skip to content

Commit

Permalink
Add support for await in MDX
Browse files Browse the repository at this point in the history
This likely doesn’t work in your JSX runtime.
But if you type `await`, it would currently always be invalid.
Now it turns into an `async` function that doesn’t crash.
If your runtime supports promises, MDX will support it too.

Closes GH-2242.
  • Loading branch information
wooorm committed Oct 19, 2023
1 parent 48f0319 commit 44fd9ca
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
24 changes: 24 additions & 0 deletions packages/mdx/lib/plugin/recma-document.js
Original file line number Diff line number Diff line change
Expand Up @@ -602,9 +602,33 @@ export function recmaDocument(options) {
argument = argument.children[0]
}

let awaitExpression = false

walk(argument, {
enter(node) {
if (
node.type === 'ArrowFunctionExpression' ||
node.type === 'FunctionDeclaration' ||
node.type === 'FunctionExpression'
) {
return this.skip()
}

if (
node.type === 'AwaitExpression' ||
/* c8 ignore next 2 -- can only occur in a function (which then can
* only be async, so skipped it) */
(node.type === 'ForOfStatement' && node.await)
) {
awaitExpression = true
}
}
})

return [
{
type: 'FunctionDeclaration',
async: awaitExpression,
id: {type: 'Identifier', name: '_createMdxContent'},
params: [{type: 'Identifier', name: 'props'}],
body: {
Expand Down
36 changes: 36 additions & 0 deletions packages/mdx/test/compile.js
Original file line number Diff line number Diff line change
Expand Up @@ -973,6 +973,42 @@ test('@mdx-js/mdx: compile', async function (t) {
}
)

await t.test(
'should support an `await` expression in content (GH-2242)',
async function () {
const element = React.createElement(
await run(await compile('{await Promise.resolve(42)}'))
)

try {
// Not supported yet by React, so it throws.
renderToStaticMarkup(element)
assert.fail()
} catch (error) {
assert.match(
String(error),
/Objects are not valid as a React child \(found: \[object Promise]\)/
)
}
}
)

await t.test(
'should not detect `await` inside functions (GH-2242)',
async function () {
const value = `{(function () {
return 21
async function unused() {
await Promise.resolve(42)
}
})()}`
const element = React.createElement(await run(await compile(value)))

assert.equal(renderToStaticMarkup(element), '21')
}
)

await t.test('should support source maps', async function () {
const base = new URL('context/', import.meta.url)
const url = new URL('sourcemap.js', base)
Expand Down

1 comment on commit 44fd9ca

@vercel
Copy link

@vercel vercel bot commented on 44fd9ca Oct 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

mdx – ./

mdx-git-main-mdx.vercel.app
mdxjs.com
mdx-mdx.vercel.app
v2.mdxjs.com

Please sign in to comment.