You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js14中MDXRemote无法加载next.config.mjs配置的MDX插件问题

解决Next.js14中MDXRemote插件不生效及类型错误问题

核心原因

next.config.mjs中配置的MDX插件(如remarkGfm、rehypeSlug)仅作用于项目文件系统中的.mdx页面文件,由Next.js编译流程处理。而MDXRemote处理的是从数据库动态获取的字符串内容,不会自动读取这些全局配置,必须在序列化阶段手动配置插件。

步骤1:安装依赖

确保安装兼容Next.js14的版本:

npm install next-mdx-remote remark-gfm rehype-slug rehype-autolink-headings

步骤2:在Server Action中序列化内容

在Server Action里获取内容后,使用next-mdx-remote/serialize函数处理,同时配置所需插件:

'use server';

import { serialize } from 'next-mdx-remote/serialize';
import remarkGfm from 'remark-gfm';
import rehypeSlug from 'rehype-slug';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';

export async function fetchAndSerializeMdx() {
  // 替换为从数据库获取MDX字符串的逻辑
  const rawMdx = `# 测试MDX内容

这是**加粗文本**,下面是GFM表格:

| 列1 | 列2 |
|-----|-----|
| 值1 | 值2 |

## 二级标题
`;

  return await serialize(rawMdx, {
    mdxOptions: {
      remarkPlugins: [remarkGfm],
      rehypePlugins: [
        rehypeSlug,
        // 给锚点链接添加自定义配置
        [rehypeAutolinkHeadings, {
          behavior: 'wrap',
          properties: { className: ['anchor'] }
        }]
      ],
      format: 'mdx' // 明确格式为mdx
    }
  });
}

步骤3:在页面组件中渲染MDXRemote

在Server Component中调用Server Action,传入序列化后的内容:

import { MDXRemote } from 'next-mdx-remote';
import { fetchAndSerializeMdx } from './actions';

export default async function MdxPage() {
  const serializedMdx = await fetchAndSerializeMdx();
  
  return (
    <div className="max-w-3xl mx-auto p-6">
      <MDXRemote {...serializedMdx} />
    </div>
  );
}

解决类型错误

如果遇到插件类型不匹配的问题:

  1. 确保所有插件安装的是最新稳定版,新版本通常修复了类型定义问题
  2. 在tsconfig.json中临时开启"skipLibCheck": true(仅当第三方库类型冲突时使用)
  3. 手动导入插件类型并标注:
import type { Options as RehypeAutolinkOptions } from 'rehype-autolink-headings';

// 在rehypePlugins中使用类型断言
[rehypeAutolinkHeadings, {
  behavior: 'wrap' as const,
  properties: { className: ['anchor'] }
} as RehypeAutolinkOptions]

内容的提问来源于stack exchange,提问作者kiwon kim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 19:32:38