mdx-js / mdx

Markdown for the component era
https://mdxjs.com
MIT License
17.72k stars 1.14k forks source link

Feature idea: @mdx-js/register #1059

Closed mariusGundersen closed 3 years ago

mariusGundersen commented 4 years ago

Subject of the feature

I've tried to use mdx for my very simple gulp based static site, and found it rather hard to get started. I realize this is my own fault, but I found it interesting to mess around and try to get it all to work. I based my code on the do it yourself section of the getting started guide, and with a bit of tweaking I got it to work, but I think it could be much simpler. The major problem I had was with nodes loading of jsx and mdx files and getting them transpiled to js code that node could execute.

Problem

There doesn't seem to be any package equivalent to @babel/register or esm for loading mdx files in node and running it. This would be very useful for static site generators, which can then run the mdx code directly in node.

Possible solution

I've messed around and gotten the following to work:

const babelConfig = {
  presets: [
    [
      '@babel/preset-env',
      {
        modules: 'cjs'
      }
    ]
  ]
};
require.extensions['.mdx'] = function (module, filename) {
    const content = fs.readFileSync(filename, 'utf8');
    const jsx = mdx.sync(content);
    const { code } = babel.transformSync("import { mdx } from '@mdx-js/react';\n" + jsx, babelConfig);
    module._compile(code, filename);
};
require.extensions['.jsx'] = function (module, filename) {
    const jsx = fs.readFileSync(filename, 'utf8');
    const { code } = babel.transformSync(jsx, babelConfig);
    module._compile(code, filename);
};

With this in place importing .jsx and .mdx files works, recursively, and I was able to use gulp to compile mdx into html.

It might be useful for others too if there was an npm package like @mdx-js/register that could be used to compile mdx files to js on the fly.

wooorm commented 4 years ago

Interesting idea! I definitely agree with the problem: MDX should be easier to use. I was thinking of an mdx cli that would take a .mdx file and compile it to a .js file.

I’m not sure about this approach. require.extentensions is deprecated with good reason!

mariusGundersen commented 4 years ago

I tried to look for alternatives to require.extensions but as far as I can tell it is the way that babel/register does it still, since there isn't really a good alternative.

wooorm commented 3 years ago

It doesn’t seem that there is any interest to create and maintain such a project here. Hence, I’ll close this. But it remains an interesting idea and I can imagine it existing in userland. I personally do think it’s a somewhat bad idea though, for performance reasons: require.extensions is deprecated for a good reason.