frontarm / mdx-util

Utilities for working with MDX

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to import an image?

nvenegas opened this issue · comments

Hi

I'm having trouble importing an image (so that webpack can process it) and including that image in the rendered markdown, e.g., something like

import logo from './images/logo.png';

![Logo]({logo})

since bracess ({logo} above) aren't treated as JSX in inline markdown.

Any ideas about how to achieve this?

In the compiled JavaScript for that document I essentially need


import logo from './images/logo.png';

  img({"src": logo, "alt": "Logo"}),

rather than


import logo from './images/logo.png';

  img({"src": "{logo}", "alt": "Logo"}),

(Note the quotes and braces around the "src" property.)

If you're using mdxc-loader, you should just be able to do this:

![Logo](./images/logo.png)

mxdc-loader will automatically require images and inject the path into the src attribute.

If you're not using mdxc-loader, you can use this plugin with MDXC to get the same effect:

function mdImageReplacer(md) {
  md.core.ruler.push('imageReplacer', function(state) {
    function applyFilterToTokenHierarchy(token) {
      if (token.children) {
        token.children.map(applyFilterToTokenHierarchy);
      }

      if (token.type === 'image') {
        const src = token.attrGet('src')

        if(!loaderUtils.isUrlRequest(src)) return;

        const uri = url.parse(src);
        uri.hash = null;
        token.attrSet('src', { __jsx: 'require("'+uri.format()+'")' });
      }
    }

    state.tokens.map(applyFilterToTokenHierarchy);
  })
}

let md = new MDXC(options).use(mdImageReplacer)