Support for server-side rendering via a Babel plugin?
See original GitHub issueThis project is super cool! I was just trying to figure out the best way to add markdown support to the JSX-based static site generator I’m working on and then I found this—it’s exactly what I’m looking for!
I’m struggling to figure out how to use it, though. I see that there is a Webpack loader, but I’m not using Webpack—the files aren’t being bundled for the browser. I see there is also an API for transforming MDX strings/files, but the problem is I need to actually require/run the JavaScript locally, because the JSX/MDX is being rendered server-side by React.
I think the general thing people do is hook into Node’s require
using babel-register
.
babelRegister({
extensions: [".jsx"],
presets: [
"react",
[
"env",
{
node: "current",
}
]
],
})
Then you can require
the JSX file/module and render it. If the module requires/imports other files they’ll also get transpiled because of babel-register
.
let component = require(modulePath)
component = component.default || component
let element = React.createElement(component)
return ReactDOMServer.renderToStaticMarkup(element)
I found a relatively old project babel-plugin-transform-mdx. I tried using it but it seems to be broken.
❯ cat test.mdx
# Hello, world!
❯ babel --plugins transform-mdx test.mdx
SyntaxError: test.mdx: Unexpected character '#' (1:0)
> 1 | # Hello, world!
| ^
2 |
I’ve got some experience with ASTs so I’d normally get my hands dirty and figure out how to make this work, but after reading the MDX transform in that repo and the JSX transform included with Babel, I’m finding the barrier to entry to be extremely high. 😞
Some time ago JSX became ubiquitous enough that it seemingly made sense for Babel to take ownership of JSX transformation. Since MDX is dependent on (or a sibling of) JSX, it makes sense to me that it should be usable in the same way that JSX is. Does the MDX team agree? Would you be willing to add support for a Babel plugin? 🙏
Issue Analytics
- State:
- Created 5 years ago
- Comments:8 (8 by maintainers)
Top GitHub Comments
Alright, here’s what I wound up doing.
The first part is setting up the transformation hook.
The second part is actually importing/requiring the file which triggers the transformation.
This isn’t the exact code—I’ve simplified it to make it easier to understand, but this is the general idea. Also this uses ES6. You’ll need to convert to CommonJS or use
esm
.Feel free to share the solution you figure out here 🙏