我正在我的 Next.js 应用程序中实现一个由 MDX 驱动的博客。在我的博客中,我使用两个
rehype
插件:rehype-slug
和 rehype-autolink-headings
将标题的链接添加回自身,但问题是 rehype-slug
没有向标题添加 id。
我已经安装了rehype-slug
:我已将
rehypeSlug
添加到
rehypePlugins
数组中。这是我的
next-config.mjs
文件:
import createMDX from '@next/mdx'
import remarkFrontmatter from 'remark-frontmatter'
import rehypeSlug from 'rehype-slug'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
/** @type {import('next').NextConfig} */
const nextConfig = {
pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'],
}
const withMDX = createMDX({
options: {
remarkPlugins: [remarkFrontmatter],
rehypePlugins: [
rehypeSlug,
[
rehypeAutolinkHeadings,
{
behavior: 'append',
properties: {
className: ['anchor-link'],
title: 'Permalink to this heading',
},
content: {
type: 'element',
tagName: 'span',
properties: { className: ['anchor-icon'] },
children: [{ type: 'text', value: '#' }],
},
},
],
],
},
})
export default withMDX(nextConfig)
这是博客文章示例:注意
Second heading
是 H2 标头。如果我在开发者工具中检查它,我发现它没有任何 ID(如下所示):我做错了什么?我是否缺少任何配置?
我的猜测是,您已经在
mdx-components
文件中设置了映射到本机 HTML 的自定义元素例如
h2: ({ children }) => <h2 className="text-gray-900 ">{children}</h2>,
您可能想将其更新为:
h2: ({ id, children }) => (
<h2 id={id} className="text-2xl text-gray-900 font-bold mt-8">
{children}
</h2>
),
问题在于 id
未传递给自定义元素。另一种方法是使用展开运算符来展开所有道具
h2: (props) => (
<h2 className="text-2xl text-gray-900 font-bold mt-8" {...props}>
{props.children}
</h2>
),