Which acorn options? #2140
-
I want to inject this element: export default (props) => <_Default {...props} tableOfContents={tableOfContents} apiComponents={apiComponents}>{props.children}</_Default> But, when I do this I get an error 'Unexpected Token': import { parse } from 'acorn';
const withLayouts = () => {
return (tree) => {
tree.children.push({
type: 'mdxjsEsm',
data: {
estree: parse(
`export default (props) => <_Default {...props} tableOfContents={tableOfContents} apiComponents={apiComponents}>{props.children}</_Default>`,
{
sourceType: 'module',
ecmaVersion: 2020,
}
)
}
});
};
export default withLayouts; I know this line of code works when I put it in the mdx file. Am I using the correct options? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 6 replies
-
Can you share more about the error? |
Beta Was this translation helpful? Give feedback.
-
It looks like you’re not actually interested in parsing JavaScript using acorn. Your code parses a hardcoded string of JavaScript with JSX. I recommend to paste the code into https://astexplorer.net (make sure to use the JavaScript language and acorn parser), then copy the JSON output on the side and strip any positional information. I suspect this is a minimal scenario and your real use case contains some variables. Once you get used working with the AST you’ll find it to be much safer to use and more powerful than string manipulations. For an example of how to use this, you can have a look at If you really do need to parse JavaScript from a string and it may contain JSX, you should use |
Beta Was this translation helpful? Give feedback.
It looks like you’re not actually interested in parsing JavaScript using acorn. Your code parses a hardcoded string of JavaScript with JSX.
I recommend to paste the code into https://astexplorer.net (make sure to use the JavaScript language and acorn parser), then copy the JSON output on the side and strip any positional information.
I suspect this is a minimal scenario and your real use case contains some variables. Once you get used working with the AST you’ll find it to be much safer to use and more powerful than string manipulations. For an example of how to use this, you can have a look at
remark-mdx-frontmatter
.If you really do need to parse JavaScript from a string and it may cont…