recma-mdx-import-media
v1.2.4
Published
Recma plugin to turn media relative paths into import declarations for both markdown and html syntax in MDX
Maintainers
Readme
A robust Next.js newsletter Next.js Weekly is sponsoring me 💖

Become a sponsor 🚀
If you find recma-mdx-import-media useful in your projects, consider supporting my work.
Your sponsorship means a lot 💖
My sponsors are going to be featured here and on my sponsor wall.
A warm thanks 🙌 to @ErfanEbrahimnia, @recepkyk, and @LSeaburg for the support!
Thank you for supporting open source! 🙌
recma-mdx-import-media
This package is a unified (recma) plugin that turns media relative paths into import declarations for both markdown and html syntax in MDX
unified is a project that transforms content with abstract syntax trees (ASTs) using the new parser micromark. recma adds support for producing a javascript code by transforming esast which stands for Ecma Script Abstract Syntax Tree (AST) that is used in production of compiled source for the MDX.
When should I use this?
You can use recma-mdx-import-media if you want to include media/asset with relative path using markdown syntax or html syntax in MDX, without providing an import statement, such as:

<img src="./image.png" alt="alt" />

<img src="../blog-assets/image.png" alt="alt" />Because, recma-mdx-import-media creates import statements and assigns an identifier into proper element in the compiled source.
recma-mdx-import-media only processes relative paths (starting with ./ or ../ or direct file name); leaving protocol-like patterns (like http://), root-relative URLs (like /pathname), and absolute paths (file:///) unchanged.
You might run into issues because bundlers like Webpack and Vite don't natively recognize these references (.png, .jpeg etc.), they only handle imports. recma-mdx-import-media bridges that gap by converting media relative references into import declarations in the compiled MDX source, ensuring bundlers can process them correctly, for both markdown and HTML syntax.
The list of the tags and attributes that recma-mdx-import-media process
img-->src,srcsetvideo-->src,posteraudio-->srcsource-->src,srcsetembed-->srctrack-->srcinput[type="image"]-->srcscript-->src
recma-mdx-import-media supports meta information (#hash and ?querystring) on the asset path.
During process, the meta information in the relative path is stripped out in the import statement.
In order you process the meta information for further process, it is added as a property into the asset as data-meta for src and poster attributes, but it preserved in srcset instead of passing it to data-meta.
Installation
This package is suitable for ESM only. In Node.js (version 18+), install with npm:
npm install recma-mdx-import-mediaor
yarn add recma-mdx-import-mediaUsage
Say we have the following file, example.mdx,

<img src="../../image.png" alt="alt" />And our module, example.js, looks as follows:
import { read } from "to-vfile";
import { compile } from "@mdx-js/mdx";
import recmaMdxImportMedia from "recma-mdx-import-media";
main();
async function main() {
const source = await read("example.mdx");
const compiledSource = await compile(source, {
recmaPlugins: [recmaMdxImportMedia],
});
return String(compiledSource);
}Now, running node example.js produces the compiled source like below:
// ...
+ import imagepng$recmamdximport from "./image.png";
+ import imagepng_1$recmamdximport from "../../image.png";
function _createMdxContent(props) {
const _components = {
img: "img",
p: "p",
...props.components
};
return _jsxs(_Fragment, {
children: [_jsx(_components.p, {
children: _jsx(_components.img, {
- src: "./image.png",
+ src: imagepng$recmamdximport,
alt: "alt"
})
}), "\\n", _jsx("img", {
- src: "../../image.png",
+ src: imagepng_1$recmamdximport,
alt: "alt"
})]
});
}
// ...This is roughly equivalent with:
import imagepng$recmamdximport from "./image.png";
import imagepng_1$recmamdximport from "../../image.png";
export default function MDXContent() {
return (
<p>
<img alt="alt" src={imagepng$recmamdximport} />
<img alt="alt" src={imagepng_1$recmamdximport} />
</p>
)
}If you want to resolve the relative paths (starts with ./ or ../) of the assets for further process, you are recommended to use recma-mdx-change-imports.
Options
All options are optional and have default values.
export type ImportMediaOptions = {
excludeSyntax?: Array<"markdown" | "html">; // default is empty array []
};excludeSyntax
It is an array option to exlude markdown or html syntax or both. The option are self-explainotary.
use(recmaMdxImportMedia, { excludeSyntax: ["html"] } as ImportMediaOptions);Now, <img /> like html syntax will be excluded.
use(recmaMdxImportMedia, { excludeSyntax: ["markdown"] } as ImportMediaOptions);Now, ![]()) like markdown syntax will be excluded.
use(recmaMdxImportMedia, { excludeSyntax: ["html", "markdown"] } as ImportMediaOptions);Now, both html and markdown syntax will be excluded. The plugin becomes effectless.
Syntax tree
This plugin only modifies the ESAST (Ecma Script Abstract Syntax Tree) as explained.
Types
This package is fully typed with TypeScript. The plugin options is exported as ImportMediaOptions.
Compatibility
This plugin works with unified version 6+. It is compatible with mdx version 3+.
Security
Use of recma-mdx-import-media does not involve user content so there are no openings for cross-site scripting (XSS) attacks.
My Plugins
I like to contribute the Unified / Remark / MDX ecosystem, so I recommend you to have a look my plugins.
My Remark Plugins
remark-flexible-code-titles– Remark plugin to add titles or/and containers for the code blocks with customizable propertiesremark-flexible-containers– Remark plugin to add custom containers with customizable properties in markdownremark-ins– Remark plugin to addinselement in markdownremark-flexible-paragraphs– Remark plugin to add custom paragraphs with customizable properties in markdownremark-flexible-markers– Remark plugin to add custommarkelement with customizable properties in markdownremark-flexible-toc– Remark plugin to expose the table of contents viavfile.dataor via an option referenceremark-mdx-remove-esm– Remark plugin to remove import and/or export statements (mdxjsEsm)remark-mdx-remove-expressions– Remark plugin to remove MDX expressions within curlybraces {} in MDX content
My Rehype Plugins
rehype-pre-language– Rehype plugin to add language information as a property topreelementrehype-highlight-code-lines– Rehype plugin to add line numbers to code blocks and allow highlighting of desired code linesrehype-code-meta– Rehype plugin to copycode.data.metatocode.properties.metastringrehype-image-toolkit– Rehype plugin to enhance Markdown image syntax![]()and Markdown/MDX media elements (<img>,<audio>,<video>) by auto-linking bracketed or parenthesized image URLs, wrapping them in<figure>with optional captions, unwrapping images/videos/audio from paragraph, parsing directives in title for styling and adding attributes, and dynamically converting images into<video>or<audio>elements based on file extension.
My Recma Plugins
recma-mdx-escape-missing-components– Recma plugin to set the default value() => nullfor the Components in MDX in case of missing or not provided so as not to throw an errorrecma-mdx-change-props– Recma plugin to change thepropsparameter into the_propsin thefunction _createMdxContent(props) {/* */}in the compiled source in order to be able to use{props.foo}like expressions. It is useful for thenext-mdx-remoteornext-mdx-remote-clientusers innextjsapplications.recma-mdx-change-imports– Recma plugin to convert import declarations for assets and media with relative links into variable declarations with string URLs, enabling direct asset URL resolution in compiled MDX.recma-mdx-import-media– Recma plugin to turn media relative paths into import declarations for both markdown and html syntax in MDX.recma-mdx-import-react– Recma plugin to ensure gettingReactinstance from the arguments and to make the runtime props{React, jsx, jsxs, jsxDev, Fragment}is available in the dynamically imported components in the compiled source of MDX.recma-mdx-html-override– Recma plugin to allow selected raw HTML elements to be overridden via MDX components.recma-mdx-interpolate– Recma plugin to enable interpolation of identifiers wrapped in curly braces within thealt,src,href, andtitleattributes of markdown link and image syntax in MDX.
License
MIT License © ipikuka
