#How do I attach Tailwind classes to markdown images, with the experimental Assets integration?

6 messages · Page 1 of 1 (latest)

tight wolf
#

This is what I'm currently using, in my .mdx file:

import { Image } from "astro:assets";
<Image
    class="max-w-[15rem] mx-auto sm:w-1/4 sm:float-left m-5 sm:m-0 sm:mr-5 rounded-md"
    src="/src/assets/image.jpeg"
    alt=""
    format="webp"
    height={426}
    width={340}
/>

There's got to be a better way to write this in markdown. Would it be a good idea to use stylesheets? I've also read about shortcuts with pandoc but I've looked through rehype and remark plugins and haven't found anything. (https://garrettgman.github.io/rmarkdown/authoring_pandoc_markdown.html#header-identifiers)

Any ideas?

obtuse pine
#

You'll need a remark plugin for this. If the classes are static, you could use normal CSS otherwise

tight wolf
#

What remark plugin?

sick badge
#

I'm using a custom Image component to wrap the assets image component.
So if you do go down the remark plugin, you could do something similar to this:

I'm not sure if this is the most optimal way of doing it but it works for me
What it does is replaces the default Image import that got added in https://github.com/withastro/astro/pull/6824 and then points to my custom component that then handles it
Then in markdown you just use the image like you normally would ![My Image](/src/assets/image.jpeg)

const isNodeAstroImage = (node: MdxjsEsm): boolean => {
    const estreeBody = node.data?.estree?.body[0] as ImportDeclaration;
    if (estreeBody === undefined) return false;
    if (estreeBody.source?.type !== 'Literal' || estreeBody.source?.type === 'astro:assets') return false;
    return estreeBody.specifiers[0]?.local?.name === '__AstroImage__';
};

const replaceAstroImage = (): Transformer => (tree) => {
    const importsStatements: MdxjsEsm[] = [];
    visit(tree, 'mdxjsEsm', (node: MdxjsEsm) => {
        if (isNodeAstroImage(node)) importsStatements.push(node);
    });
    importsStatements.forEach((n) => {
        const index = (tree.children as Array<Node>).indexOf(n);
        (tree.children as Array<Node>).splice(index, 1);
    });
    (tree.children as Array<Node>).unshift(jsToTreeNode(`import { default as __AstroImage__ } from '~components/Image.astro';`));
};

export default replaceAstroImage;

Full gist https://gist.github.com/roryclaasen/f69b1a37481429a16789a51dc65a1248 due to discord message length

sick badge
#

It's a custom remark plugin that you could use to replace the default Astro Image component that gets imported. It would allow you to use a custom image component that you could then use to add tailwind classes to, wrap the image component etc, without the need to import the component within the MDX file