Pass mdast
tree to mdx compile?
#2483
Replies: 2 comments 2 replies
-
Hey there 👋 If have import { createProcessor } from '@mdx-js/mdx'
const processor = createProcessor(options)
const estree = await processor.run(mdast, vfile)
const js = String(processor.compile(estree)) Depending on your use case you may want to compile your |
Beta Was this translation helpful? Give feedback.
-
Hey @remcohaszing, this seems like a good solution, thank you. However I'm a little bit stumped...
I've tried various things but so far I'm unable to wire these two parts together successfully: import { Root } from 'mdast';
import { createProcessor, ProcessorOptions } from '@mdx-js/mdx';
import * as runtime from 'preact/jsx-runtime';
// import { createContext } from './context';
// import { createRehypePlugins } from './rehype-plugins';
// import { createRemarkPlugins } from './remark-plugins';
// @ts-expect-error: typescript doesn't like preact/jsx-runtime for unknown reasons
const options: ProcessorOptions = {
...runtime,
};
options.outputFormat = 'function-body';
export async function compileMdastToJs(mdast: Root) {
// const ctx = createContext();
// options.remarkPlugins = createRemarkPlugins(ctx);
// options.rehypePlugins = createRehypePlugins(ctx);
const processor = createProcessor(options);
const estree = await processor.run(mdast);
return {
jsString: String(processor.stringify(estree)), // <-- I guess stringify is not this right method to use here
};
} and Preact component: import { Fragment } from 'preact';
import { useEffect, useState } from 'preact/hooks';
import { RunOptions, run } from '@mdx-js/mdx';
import { MDXComponents, MDXModule } from 'mdx/types';
import * as runtime from 'preact/jsx-runtime';
// @ts-expect-error: preact/jsx-runtime is incompatible for unknown reasons
const options: RunOptions = {
...runtime,
};
type Props = {
jsString: string;
};
export function Article({ jsString }: Props) {
const [MDX, setMDX] = useState<MDXModule | null>(null);
const MDXContent = MDX ? MDX.default : Fragment;
useEffect(() => {
(async () => {
setMDX(await run(jsString, options));
})();
}, [jsString]);
return (
<article>
<MDXContent />
</article>
);
} |
Beta Was this translation helpful? Give feedback.
-
Hi there,
I am working in long documents in either Markdown or LaTeX which eventually get
eval
ed withmdx
in a Preact environment.It may be an unusual case, but by the time I get to the final
mdx
step, my data is already inmdast
form.It would be nice to have the option to pass the
mdast
tree tocompile
without the need to serialise and parse it again.Thanks.
Beta Was this translation helpful? Give feedback.
All reactions