Using Nuxt Image with Nuxt Content
published 2023/4/26
The Nuxt Image module allows us to create
easy responsive images with sizes
and srcset
attributes. Making the module work with Nuxt Content can be done with a custom content component.
Here's the component I added to my project (based on Nuxt Content's ProseImg component):
<!-- ./components/content/ResponsiveImg.vue -->
<template>
<NuxtImg
:src="refinedSrc"
:alt="alt"
:sizes="sizes"
:class="class"
:format="format"
:loading="loading"
/>
</template>
<script setup lang="ts">
import { withBase } from 'ufo'
import { useRuntimeConfig, computed } from '#imports'
const props = defineProps({
src: {
type: String,
default: '',
},
alt: {
type: String,
default: '',
},
sizes: {
type: String,
default: 'xs:100vw md:1004px',
},
class: {
type: String,
default: 'rounded-md md:w-[502px]',
},
format: {
type: String,
default: 'webp',
},
loading: {
type: String,
default: 'lazy',
},
})
const refinedSrc = computed(() => {
if (props.src?.startsWith('/') && !props.src.startsWith('//')) {
return withBase(props.src, useRuntimeConfig().app.baseURL)
}
return props.src
})
</script>
Now, in my post Markdown (using MDC), I can use this new component:
:responsive-img{src="/in/public/dir/img.jpg" alt="My image"}
This renders the following HTML:
<img
src="/_ipx/w_1004&f_webp/in/public/dir/img.jpg"
alt="My image"
loading="lazy"
data-nuxt-img=""
sizes="(max-width: 320px) 100vw, 1004px"
srcset="
/_ipx/w_320&f_webp/in/public/dir/img.jpg 320w,
/_ipx/w_1004&f_webp/in/public/dir/img.jpg 1004w
"
class="rounded-md md:w-[502px]"
/>