How to compile an MDX string to render later in React (server and client)? #1452
-
I'm looking for help understanding the usage of My use-case works like this:
Important to note above is the I have made some progress on how to write the compiler function, but I cannot get my head around the render process. Virtually all packages and examples I've found seem to assume you are loading MDX content as a component from an Can anyone help with this? 🙏 This is about as far as I got with the compiler... const mdx = require('@mdx-js/mdx');
const { transformAsync } = require('@babel/core');
const presetEnv = require('@babel/preset-env');
const presetReact = require('@babel/preset-react');
const pluginRemoveExport = require('babel-plugin-remove-export-keywords');
const mdxHeader = `
import React from 'react'
import {mdx} from '@mdx-js/react'
`;
const mdxOptions = {
remarkPlugins: [],
rehypePlugins: [],
skipExport: true,
};
const envOptions = { targets: { node: 'current' }, modules: false };
const babelOptions = {
presets: [[presetEnv, envOptions], presetReact],
plugins: [pluginRemoveExport, pluginMdxBrowser],
};
async function mdxCompile(mdxSrc) {
const mdxJsx = await mdx(mdxSrc, mdxOptions);
const { code } = await transformAsync(`${mdxHeader}\n${mdxJsx}`.trim(), babelOptions);
return code;
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Taking a step back.
I'm not sure I understand this.
The return value of async function mdxCompile(mdxSrc) {
const mdxJsx = await mdx(mdxSrc, mdxOptions);
const { code } = await transformAsync(`${mdxHeader}\n${mdxJsx}`.trim(), babelOptions);
return code;
} is the JavaScript for a React component. |
Beta Was this translation helpful? Give feedback.
Taking a step back.
This doesn't really seem to be an MDX question, MDX compiles JS/JSX, which is what your example does.
The question seems to be more "How do I dynamically load React components?", or even more broadly "How do I dynamically load JavaScript?".
Both of which are outside the scope of MDX, and generally would be handled with EcmaScript Dynamic Modules, or another loader like CJS, AMD, SystemJS, etc.