An MDX rehype plugin for turning media paths into imports.
MIT License
An MDX rehype plugin for turning media paths into imports.
npm install rehype-mdx-import-media
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.
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:
md
formatrehype-raw
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
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>
)
}
The default export is a rehype plugin.
attributes
(object
): HTML element attributes that should be processed. The key is the HTMLelementAttributeNameCase
('html' | 'react'
): The casing to use for attribute names. This'react'
)preserveHash
('both' | 'import' | 'jsx' | 'none'
): Where to keep URL hash. (Default:'import'
)
both
: Keep the URL hash on both the import source and the JSX prop.import
: Only keep the URL hash on the import source.jsx
: Only keep the URL hash on the JSX prop.none
: Remove the URL hash.preserveQuery
('both' | 'import' | 'jsx' | 'none'
): Where to keep query parameters. (Default:'import'
)
both
: Keep the query parameters on both the import source and the JSX prop.import
: Only keep the query parameters on the import source.jsx
: Only keep the query parameters on the JSX prop.none
: Remove the query parameters.resolve
(boolean
): By default imports are resolved relative to the markdown file. This matchesnode_modules
. If this is disabled, local images can still be imported by prepending the path./.
. (Default: true
).This project is compatible with MDX 3 and Node.js 18 or greater.