1
2
3
4
5
6
7
8
9
10
| //vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import mdx from "@mdx-js/rollup";
export default defineConfig(async () => {
return {
plugins: [react(), mdx()],
};
});
|
2. We need the provider of MDX to wrap the app to apply the imported *.mdx#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| //App.ts
import { MDXProvider } from "@mdx-js/react";
function App() {
return (
<>
<MDXProvider>
<TestMarkdown />
</MDXProvider>
</>
);
}
export default App;
|
Note: This doesnot support code higlighting and table; we need rehype-highlight, remark-gfm respectively for that
1
2
3
4
5
6
7
8
9
10
11
12
13
| //vite.config.ts
import remarkGfm from "remark-gfm";
export default defineConfig(async () => {
return {
plugins: [
react(),
mdx({
remarkPlugins: [remarkGfm],
}),
],
};
});
|
4. Now to add code block syntax highlighting, it could be done in 2 ways; runtime and compile time.#
Compile time : we need rehype guide.
Run time : react-syntax-highlighter
For react-syntax-highlighter
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| interface CodeProps {
className?: string;
children?: React.ReactNode;
}
// Custom syntax highlighting component
function CodeBlock({ className, children, ...props }: CodeProps) {
const match = /language-(\w+)/.exec(className || "");
return match ? (
<SyntaxHighlighter
language={match[1]}
PreTag="div"
{...props}
style={atelierCaveDark}
showLineNumbers
>
{String(children).trim()}
</SyntaxHighlighter>
) : (
<code className={className} {...props}>
{children}
</code>
);
}
|
1
| <BlogComponent components={{ code: CodeBlock }} />
|
Above guide is to have syntax highlighting(runtime), gfm, mdx in react.
MDX from node.js (remote location)#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| const filePath = path.join(
__dirname,
"public",
"mdx-files",
`${req.params.slug}.mdx`
);
const mdxContent = readFileSync(filePath, "utf-8");
const { code, frontmatter } = await bundleMDX({
source: mdxContent,
mdxOptions(options) {
options.remarkPlugins = [...(options.remarkPlugins ?? []), remarkGfm];
options.development = false;
return options;
},
});
res.json({ code, frontmatter });
|
1
2
3
4
5
6
7
8
9
10
11
12
| const MDXContent = useMemo(() => {
if (fetchedPost?.code) {
try {
// This evaluates the code and returns a React component
return getMDXComponent(fetchedPost.code);
} catch (error) {
console.error("Error creating MDX component:", error);
return null;
}
}
return null;
}, [fetchedPost]);
|
1
| <MDXContent components={{ code: CodeBlock }} />
|