使用next-mdx-remote时MDX引入React组件编译失败求助
解决NextJS中next-mdx-remote引入React组件的报错问题
在NextJS中使用next-mdx-remote处理MDX内容时,普通MDX语法可正常渲染,但在MDX文件中引入<CodeBlock>这类自定义React组件时,会抛出错误:
Error: Expected component
to be defined: you likely forgot to import, pass, or provide it. It’s referenced in your code at 317:1-317:24
有效示例(可正常运行)
--- title: 'First Blog Post' author: 'Me' publishDate: 'Nov 4th, 2023' --- # This is our first post Here is a regular paragraph here is a list: - Item one - Item two - Item three ## This is an h2 element
无效示例(编译失败)
--- title: 'First Blog Post' author: 'Me' publishDate: 'Nov 4th, 2023' --- # This is our first post Here is a regular paragraph here is a list: - Item one - Item two - Item three <CodeBlock></CodeBlock> ## This is an h2 element
解决方法
要让MDX识别自定义组件,需完成以下步骤:
1. 在渲染MDX时传入组件
在articles/[slug]/page.js中,使用MDXRemote组件时,通过components属性传入自定义组件:
首先导入CodeBlock组件:
import CodeBlock from '@/components/CodeBlock';
然后在MDXRemote中配置:
<MDXRemote source={content} components={{ CodeBlock }} />
2. 配置全局MDX组件(可选)
如果使用了mdx-components.js全局配置文件,需在该文件中导出包含CodeBlock的组件映射:
import CodeBlock from '@/components/CodeBlock'; export function useMDXComponents(components) { return { ...components, CodeBlock, }; }
3. 确认组件导入路径正确
检查CodeBlock组件的导入路径,确保路径无误,避免因路径错误导致组件未加载。
内容的提问来源于stack exchange,提问作者Owaiz Yusufi
相关产品推荐
相关产品推荐

