简体   繁体   中英

React components and math expressions in .mdx file are not rendering correctly in Next.js application

My custom React components when imported in a .mdx file, are not being rendered at all. The math expressions in the .mdx file either render unformatted or throw parsing errors in spite of following the configuration instructions in the Next.js ( https://nextjs.org/docs/advanced-features/using-mdx ) and MDX documentation ( https://mdxjs.com/guides/math/ ).

Here are my configurations:

//next.config.js
/** @type {import('next').NextConfig} */

const remarkMath = import('remark-math');
const rehypeKatex = import('rehype-katex');

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [remarkMath],
    rehypePlugins: [rehypeKatex],
    // If you use `MDXProvider`, uncomment the following line.
    // providerImportSource: "@mdx-js/react",
  },
})
module.exports = withMDX({
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx'],
  reactStrictMode: true
})


//package.json

  "dependencies": {
    "@mdx-js/loader": "^2.1.1",
    "@next/mdx": "^12.1.5",
    "fs": "^0.0.1-security",
    "gray-matter": "^4.0.3",
    "next": "12.1.5",
    "path": "^0.12.7",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "recharts": "^2.1.9",
    "rehype-katex": "^6.0.2",
    "remark": "^14.0.2",
    "remark-html": "^15.0.1",
    "remark-math": "^5.1.1"
  },
  "devDependencies": {
    "@types/node": "17.0.25",
    "@types/react": "18.0.5",
    "@types/react-dom": "18.0.1",
    "eslint": "8.13.0",
    "eslint-config-next": "12.1.5",
    "typescript": "4.6.3"
  }

Here is my custom Document component to allow the app to fetch the katex.min.css file:

//_document.tsx
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
    return (
        <Html>
            <Head>
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.15.3/dist/katex.min.css" integrity="sha384-KiWOvVjnN8qwAZbuQyWDIbfCLFhLXNETzBQjA/92pIowpC0d2O3nppDGQVgwd2nB" crossOrigin="anonymous"/>
            </Head>
            <body>
                <Main />
                <NextScript />
            </body>
        </Html>
    )
}

What is it that I'm not doing correctly?

If there are errors, probably you can't use require and so you didn't import the plugins successfully. You have to use import method in config file and use the MDXProvider wrap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM