Astro components wrapping @astrojs/image for easier use in MDX files.
Have a look at the blog post to learn more, how to work with optimized images in Astro MDX.
This package is a source distribution of Astro components, which ease working with images as they usually appear in markdown files, i.e.
- local images referenced by absolute file paths (relative paths are supported through the use of astro-m2dx
normalizePaths
-feature) - no additional attributes besides
alt
,src
andtitle
(art direction through the class attribute can be implemented through astro-m2dx:style
-directives
If you use Astro MDX to generate a site from Markdown files and you want to use optimized images through regular markdown image syntax, i.e. ![Alt text](./my-url.jpg)
.
The components do not rely on astro-m2dx, but are only tested in the context of it and are best used together with it.
This package is ESM only.
In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm
:
npm install astro-m2dx-image
The simplest (and least effective) use is, to simply map markdown images to the provided image component in a _components.ts
import { Image } from 'astro-m2dx-image';
export const components = {
img: Image,
};
Do not forget to enable exportComponents
and normalizePaths
in your astro-m2dx configuration.
This will give you an optimized image with all the default settings, probably it is not optimized at all, but you could take the image component as a basis to implement your own default settings.
Doing the same as above, but with the Picture
component will give you access to next generation image formats 'avif' and 'webp'.
import { Picture } from 'astro-m2dx-image';
export const components = {
img: Picture,
};
You can easily implement a custom component, by defining some default properties
---
import { Picture, PictureProps } from 'astro-m2dx-image';
const props = Astro.props as PictureProps;
const customProps: PictureProps = {
aspectRatio: 1,
loading: props.class?.includes('eager') ? 'eager' : undefined,
position: 'attention',
sizes: '(min-width: 360px) 240px, 100vw',
widths: [240, 480],
...props,
};
---
<Picture {...customProps} />
For the property loading
, you can see a typical pattern, that I use for art direction: I usually derive some properties from classes, that I attach to images, using astro-m2dx :style
-directive
![My fantastic hero image](./hero.jpg):style{.eager}
If you have the need to compute some props based on all defined props including a resolved src
property, you can configure a callback
function (props: PictureProps) => PictureProps
, that can set any property.
A typical use case would be, to limit the aspect ratio to some boundaries.
For a detailed introduction, have a look at the astro-m2dx blog post "Working with images".