The problem
I'm writing a babel plugin that modifies some JSX code at compile time.
<MyComponent >
{/* comment here */}
</MyComponent>
What I want it to do is read some local configuration and inject some code. I'm aiming for this:
import Something from '/Absolute/path/to/local/config';
// component here:
<MyComponent >
<SomeHighlyConfigDependentComponent {...withConfiguredProps} />
</MyComponent>
Everything else is fine, but I can't actually get the JSX comment. On AST explorer the AST shows up as:
{
"type": "JSXExpressionContainer",
"start": 82,
"end": 102,
"expression": {
"type": "JSXEmptyExpression",
"start": 83,
"end": 101
}
},
But this doesn't give me much information regarding the fact that:
- this is a comment
- this comment's contents are equal to
comment here
And therefore I can't reliably differentiate this comment ("please inject") from anything else.
Please don't question why I'm doing this; the pseudo code above is a very very minimal, out-of-context concept that is part of a bigger thing in my project. If you have better design alternatives or ideas feel free to comment though!
The question
Is there any way Babel could "detect" the presence of, and parse the contents of, a JSX comment? If not, can you explain why? If not, are there any lightweight alternatives I can try that allows me to do this in compile time (except brute force parsing regex, that's an absolute NO)?
Alternatives I've tried
According to this issue, I've tried this:
<MyComponent >
{ null /* comment here */}
</MyComponent>
And AST explorer parses this as
{
"type": "JSXExpressionContainer",
"start": 82,
"end": 107,
"expression": {
"type": "Literal",
"start": 83,
"end": 87,
"value": null,
"raw": "null"
}
},
And doesn't solve the problem. Failing to parse comments, I've tried this:
<MyComponent >
<div data-inject-code="SOME_CONSTANT" />
</MyComponent >
And this works, it's not extremely ideal since we'll have to document how this div does NOT appear in the DOM tree, it gets replaced, and people who actually want a wrapper div around the modified code might be confused about this behavior. Imagine coding <div data-inject-code="SOME_CONSTANT" className="flex flex-row" /> and finding their flexbox wrapper has disappeared.
If all else fails I'll use this solution. But - can you understand what I'm saying here - I'm actually more interested in the "whys" behind the problem. How does babel processes JSX comments, can I make it parse them?