-
Hi, what I want to achieve is:
output:
So I write a plugin like this: export function demoMdxPlugin() {
return tree => {
visit(tree, 'mdxJsxFlowElement', (node, index) => {
let src: string | undefined = node.attributes?.find(
attr => attr.name === 'src' && typeof attr.value === 'string'
)?.value;
if (!src) {
return;
}
const imported = `__demo_${index}`;
const importStr = `import * as ${imported} from '${getDemoModuleId(
src
)}';`;
// add import to root tree
tree.children.push({
type: 'mdxjsEsm',
value: importStr,
});
// add component children
node.children.push({
type: 'mdxJsxFlowElement',
name: `${imported}.default`,
});
return SKIP;
});
};
} But it doesn't work as expected, and throw an error in runtime:
I was wondering if there was any way to do that. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 9 replies
-
In mdx v1, it seemed like I could do this in a way like this: tree.children.unshift({
type: 'import',
value: 'import * as __demo_0 from './Button.tsx';',
}); |
Beta Was this translation helpful? Give feedback.
-
We now have a proper AST for these things. You can look at the existing plugins that use it for inspiration: https://mdxjs.com/docs/extending-mdx/#list-of-plugins. Note, from your existing attempts, the main thing is: we handle ASTs now, not strings. So the main difference is that you need to define an AST. Not a string. |
Beta Was this translation helpful? Give feedback.
-
I hope this helps someone. I'm a newb at this, so I couldn't figure out for the life of me what was going on! Thanks to your comment @wooorm, it finally clicked! I'm now using abstract-syntax-tree to parse the code into AST and inject it into the tree! import AST from "abstract-syntax-tree";
const importStr = "import Whatever from './path/to/whatever'"
const exportStr = "export default Whatever;"
tree.children.unshift(
{
type: "mdxjsEsm",
value: importStr,
data: {
estree: AST.parse(importStr),
},
},
{
type: "mdxjsEsm",
default: true,
value: exportStr,
data: {
estree: AST.parse(exportStr),
},
}
); |
Beta Was this translation helpful? Give feedback.
-
just use import Demo from './demo';
......
<MDXProvider
components={{
Demo: props => < Demo {...props} />,
}}>
{children}
</MDXProvider> |
Beta Was this translation helpful? Give feedback.
We now have a proper AST for these things. You can look at the existing plugins that use it for inspiration: https://mdxjs.com/docs/extending-mdx/#list-of-plugins.
Note, from your existing attempts, the main thing is: we handle ASTs now, not strings. So the main difference is that you need to define an AST. Not a string.