Home

Awesome

rehype-mdx-import-media

github actions codecov npm version npm downloads

An MDX rehype plugin for turning media paths into imports.

Table of Contents

Installation

npm install rehype-mdx-import-media

When should I use this?

You may want to author images in MDX using the markdown format, like so:

![alt](./image.png 'title')

You may use MDX with a bundler such as webpack or Vite. By default bundlers don’t understand how to resolve those images. They only understand how to resolve imports. This plugin solves that problem.

Also you may use MDX to load markdown files. If you reference other media in those markdown files using HTML tags, that media can be resolved by this plugin too.

Usage

This plugin takes HTML elements that refer to media content, and turns them into MDX expressions that use imports. This allows bundlers to resolve media you referenced from your code. Note that JSX elements are not HTML elements, so they are not processed. HTML elements can come from:

If this plugin finds an attribute to process, it transforms the hast element nodes into an mdxJsxTextElement node. This may prevent other rehype plugins from further processing. To avoid this, put rehype-mdx-import-media after any other rehype plugins

Example

Let’s say we have a file named example.mdx with the following contents:

![](./image.png)

The following script:

import { compile } from '@mdx-js/mdx'
import rehypeMdxImportMedia from 'rehype-mdx-import-media'
import { read } from 'to-vfile'

const { value } = await compile(await read('example.mdx'), {
  jsx: true,
  rehypePlugins: [rehypeMdxImportMedia]
})
console.log(value)

Roughly yields:

import _rehypeMdxImportMedia0 from './image.png'

export default function MDXContent() {
  return (
    <p>
      <img alt="" src={_rehypeMdxImportMedia0} />
    </p>
  )
}

API

The default export is a rehype plugin.

Options

Compatibility

This project is compatible with MDX 3 and Node.js 18 or greater.

License

MIT © Remco Haszing