在Next.js中使用MDX与rehype-highlight渲染MD代码时出现Object.hasOwn报错
问题:添加rehypeHighlight后出现TypeError: Object.hasOwn is not a function
我的配置完全基于Next.js和next-mdx-remote的官方示例,原本一切正常,但将rehypeHighlight添加到rehypePlugins数组后,出现错误:TypeError: Object.hasOwn is not a function。以下是相关代码及依赖配置:
序列化代码
import { serialize } from "next-mdx-remote/serialize"; import rehypeHighlight from "rehype-highlight" export async function getPostData(id) { const fullPath = path.join(postsDirectory, `${id}.md`); const fileContents = fs.readFileSync(fullPath, 'utf8'); // 使用gray-matter解析文章元数据 const {content, data} = matter(fileContents) const mdxSource = await serialize(content, { // 可选传入remark/rehype插件 mdxOptions: { remarkPlugins: [], rehypePlugins: [rehypeHighlight], }, scope: data, }); // 合并数据与id、内容 return { id, mdxSource, data } }
渲染代码
export async function getStaticProps({ params }) { const postData = await getPostData(params.id); return { props: { source: postData.mdxSource, postData: postData.data, } } } export default function Post({ source, postData }) { return ( <Layout> <Head> <title>{postData.title}</title> </Head> <article> <h1 className={utilStyles.headingXl}>{postData.title}</h1> <div className={utilStyles.lightText}> <Date dateString={postData.date} /> </div> <section> <MDXRemote {...source} /> </section> </article> </Layout> ); }
package.json依赖
"dependencies": { "date-fns": "^2.25.0", "eslint": "8.36.0", "eslint-config-next": "12.3.4", "gray-matter": "^4.0.2", "next": "12.3.4", "next-fonts": "^1.5.1", "next-mdx-remote": "^3.0.1", "next-routes": "^1.4.2", "react": "18.2.0", "react-dom": "18.2.0", "react-p5-wrapper": "^4.1.1", "react-unity-webgl": "^9.4.0", "react-use": "17.4.0", "rehype-highlight": "^7.0.0", "remark": "^13.0.0", "remark-html": "^13.0.2" }
解决方法
问题原因
Object.hasOwn是ES2022新增的API,你当前使用的Next.js 12.3.4对应的Node.js版本不支持这个API。而rehype-highlight@7.0.0及其依赖的包已经开始使用该特性,导致运行时报错。
方案一:降级rehype-highlight版本
将rehype-highlight降级到v6.x版本(该版本未使用ES2022特性,兼容旧版Node.js),执行以下命令:
npm install rehype-highlight@6.0.0 --save
修改后package.json中rehype-highlight的版本应为^6.0.0,重新启动项目即可。
方案二:升级Next.js版本
将Next.js升级到13.x及以上版本,新版Next.js会使用支持Object.hasOwn的Node.js版本,同时也能获得更多新特性。执行升级命令:
npm install next@latest eslint-config-next@latest --save
升级完成后重新启动项目即可。
内容的提问来源于stack exchange,提问作者SpaceBear
相关产品推荐
相关产品推荐

