Skip to content

Commit 8e7f703

Browse files
committed
Add improved error message for MDX nodes
1 parent d1d95a1 commit 8e7f703

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

lib/index.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,16 @@ import {pointStart, pointEnd} from 'unist-util-position'
5757
import {visit} from 'unist-util-visit'
5858
import {zwitch} from 'zwitch'
5959

60+
// Node types associated with MDX.
61+
// <https://github.com/mdx-js/mdx/blob/641eb91/packages/mdx/lib/node-types.js>
62+
const knownMdxNames = new Set([
63+
'mdxFlowExpression',
64+
'mdxJsxFlowElement',
65+
'mdxJsxTextElement',
66+
'mdxTextExpression',
67+
'mdxjsEsm'
68+
])
69+
6070
/** @type {ParserOptions} */
6171
const parseOptions = {sourceCodeLocationInfo: true, scriptingEnabled: false}
6272

@@ -392,8 +402,14 @@ function unknown(node_, state) {
392402
) {
393403
stitch(node, state)
394404
} else {
395-
// To do: add improved error message.
396-
throw new Error('Cannot compile `' + node.type + '` node')
405+
let extra = ''
406+
407+
if (knownMdxNames.has(node.type)) {
408+
extra =
409+
". It looks like you are using MDX nodes with `hast-util-raw` (or `rehype-raw`). If you use this because you are using remark or rehype plugins that inject `'html'` nodes, then please raise an issue with that plugin, as its a bad and slow idea. If you use this because you are using markdown syntax, then you have to configure this utility (or plugin) to pass through these nodes (see `passThrough` in docs), but you can also migrate to use the MDX syntax"
410+
}
411+
412+
throw new Error('Cannot compile `' + node.type + '` node' + extra)
397413
}
398414
}
399415

test-types.d.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,15 @@ export interface CustomLiteral extends Literal {
1010
type: 'customLiteral'
1111
}
1212

13+
export interface MdxjsEsm extends Literal {
14+
type: 'mdxjsEsm'
15+
}
16+
1317
declare module 'hast' {
1418
interface RootContentMap {
1519
customLiteral: CustomLiteral
1620
customParent: CustomParent
21+
mdxjsEsm: MdxjsEsm
1722
}
1823

1924
interface ElementContentMap {

test.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,14 @@ test('raw', () => {
2929
'should throw for unknown nodes'
3030
)
3131

32+
assert.throws(
33+
() => {
34+
raw(u('root', [u('mdxjsEsm', '')]))
35+
},
36+
/^Error: Cannot compile `mdxjsEsm` node. It looks like you are using MDX nodes/,
37+
'should throw for unknown nodes'
38+
)
39+
3240
assert.deepEqual(
3341
raw(h('#foo.bar', 'baz')),
3442
h('#foo.bar', 'baz'),

0 commit comments

Comments
 (0)