SvelteKit Dynamic Image Import: Add Images to Templates
Tags: svelte, webdev, javascript
Published: 2021-09-20 07:59:36

---
title: "SvelteKit Dynamic Image Import: Add Images to Templates"
published: "true"
description: "SvelteKit dynamic image import: how you can import and cache responsive images into a template on your Svelte app using vite-imagetools."
tags: "svelte, webdev, javascript"
canonical_url: "https://rodneylab.com/sveltekit-dynamic-image-import/"
cover_image: "https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3t6ir6gi2xo93ok2xwco.png"
---

## ✨ Introduction

Let's start by defining what we mean by SvelteKit dynamic image import by looking at a use case.  We'll then run through how to use vite's dynamic import functionality to help us out.

Before we start, I should mention that we are not talking about regular addition of images to a SvelteKit site.  For example if you write a Svelte component specifically for a given page.  Let's say an About Us page on a company site.  If you know at the time you write the component exactly which image will be included on the page, then you probably want to be looking at the article on <a aria-label="Open article on adding Next-Gen, responsive images to your Svelte Kit site" href="https://rodneylab.com/sveltekit-image-plugin/">adding responsive, Next-Gen images in SvelteKit using vite-imagetools</Linak>.

Here we are looking at cases where the page might be rendered by a template.  That template might be responsible for rendering several pages, and each of those pages may well have a different image in the browser.  This is the case even though they all come from the same template.  An example might be an online store.  You could have a template for product pages.  Each individual product page can be created by the same temple but will probably include an image of the actual product it is referring to.  This is exactly the case we are looking at here.  Now you know what this is all about, let's tackle the problem!

## 🖋 Example use Case

We'll look at a blog site as our example here.  Our template will be able to render any blog post on our site.  However to improve user experience and <a aria-label="Learn how to optimise your Svelte Kit site for search engine ranking" href="https://rodneylab.com/sveltekit-seo/">ace Search Engine Optimisation</a>, we decide to add a different featured image to each blog post.  We also want to use responsive images, with placeholders to reduce cumulative layout shift.  Finally we want to cache and have links for images used in Search Engine Optimisation (SEO) meta data. Let's summarise our needs:
 
1. Responsive images, in Next-Gen formats with <a aria-label="Learn how you can reduce Cumulative Layout Shift" href="https://rodneylab.com/sveltekit-image-plugin/">placeholders to reduce Cumulative Layout Shift</a>,

2. We have a way to specify which image we will use on each page but need the template to able to render an arbitrary image

3. Want to use vite-imagetools to do heavy lifting in generating responsive image data.

Let's try to motivate a solution next.

## 🧑🏽‍🎓 SvelteKit Dynamic Image Import Problem

With vite-imagetools, you can generate a source url just by importing an asset already saved within the project. As an example, the SvelteKit code might look like this:

```javascript
import featuredImageSrc from '$lib/assets/about/company-headquarters.jpg';
```

We could add this code to an about page, for example, though going back to our blog use case, we would need a way to specify the image dynamically.  You might already know that dynamic imports are possible with SvelteKit.  This functionality is provided by vite.  Examples are:

```javascript
const modules = import.meta.glob('./dir/*.js')
const data = await import(`../lib/assets/blog/${office}/index.json`);
```

You might include the second example in a template file, defining `office` in an import.

These work in the general case, though I had issues importing an image using `vite-imagetools` with a dynamic variable (no issues at all if we use a static path).  Here is an example of the dynamic variable case:

```javascript
// WOULD NOT WORK
const src = await import(`../lib/assets/blog/${slug}/${featuredImage}.jpg`;
```

Interestingly the following worked fine (importing a JavaScript file dynamically, rather than an image):

```javascript
imageData = await import(`../lib/assets/blog/data/${slug}.js`;
```

## 🧑🏽‍🎓 SvelteKit Dynamic Image Import Solution

I can smell a potential solution to the SvelteKit dynamic image import problem!  We can create one of these files for each blog post and in the file generate the image data as usual.  For example add something like this to the data file:

```javascript
import meta from '$lib/assets/blog/post-one/featured-image.jpg';
 
const { src, width } = meta;
 
const data = {
  src,
  width
}
 
export { data as default };
```

The downside here is that we have to write one of these files for each blog post. That might be quite onerous to do manually.  However, we could create a script to generate these files, one for each blog post.  On top we could include extra data like low resolution image placeholders as well as SEO images, generated in our script.  The script can run before every build, though in reality only needs to be changes on adding a new blog post or changing the blog images.

Here is an example blog post image data file generated using such a script:

```javascript
import meta from '$lib/assets/blog/best-medium-format-camera-for-starting-out/best-medium-format-camera-for-starting-out.jpg?width=672&metadata';
import srcsetwebp from '$lib/assets/blog/best-medium-format-camera-for-starting-out/best-medium-format-camera-for-starting-out.jpg?w=1344;672&webp&srcset';
import srcsetauto from '$lib/assets/blog/best-medium-format-camera-for-starting-out/best-medium-format-camera-for-starting-out.jpg?w=1344;672&jpeg&srcset';
import ogImage from '$lib/assets/blog/best-medium-format-camera-for-starting-out/best-medium-format-camera-for-starting-out-open-graph.jpg';
import ogSquareImage from '$lib/assets/blog/best-medium-format-camera-for-starting-out/best-medium-format-camera-for-starting-out-open-graph-square.jpg';
import twitterImage from '$lib/assets/blog/best-medium-format-camera-for-starting-out/best-medium-format-camera-for-starting-out-twitter.jpg';
 
const { height, src, width } = meta;
 
const data = {
  slug: 'best-medium-format-camera-for-starting-out',
  alt: 'Photograph of a Hasselblad medium format camera with the focusing screen exposed',
  width,
  height,
  src,
  sources: [
    { srcset: srcsetwebp, type: 'image/webp' },
    { srcset: srcsetauto, type: 'image/jpeg' },
  ],
  dominantColour: '#484848',
  placeholder:
    'data:image/jpeg;base64,/9j/2wBDAAwREhMUFBUUFBofGhUaHiIcGhohKC4jJB4hMzg/PTouKC5CRFpMPi5XRTc3VmBRVlpgZmRkQklveXFmeFtlaWf/2wBDAQgMDQwNDw8PDxFgEBIaVmBaYFpgY2NjY2BjYGBiY2NjY2NjY2NjY2NjY2JjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAAHAAoDASIAAhEBAxEB/8QAFgABAQEAAAAAAAAAAAAAAAAAAAIF/8QAFQEBAQAAAAAAAAAAAAAAAAAAAwX/2gAMAwEAAhADEAAAAM+Cev8A/8QAHBABAAEEAwAAAAAAAAAAAAAAAQIAAxMhEZGh/9oACAEBAAE/AM5u2kZDIkS48rMmtnTX/8QAFhEBAQEAAAAAAAAAAAAAAAAAAQIA/9oACAECAQE/AKtkkDf/xAAXEQEAAwAAAAAAAAAAAAAAAAABABEh/9oACAEDAQE/AHKZ/9k=',
  ogImage,
  ogSquareImage,
  twitterImage,
};
 
export { data as default };
```

Using a script, if we decide we want to use AVIF images instead of WebP or change our image widths, it is pretty easy to regenerate the data files.  Likewise if we decide to go for a plain, dominant colour placeholder instead of the low resolution one.  You can see a <a aria-label="Open the example code on the Rodney Lab Git Hub page" href="https://github.com/rodneylab/sveltekit-blog-mdx">full working example in the SvelteKit Blog MDsveX starter on the Rodney Lab GitHub page</a>.

## 🙏🏽 Feedback

Have you found the post useful? Do you have your own methods for solving this problem? Let me know your solution. Would you like to see posts on another topic instead? Get in touch with ideas for new posts. Also if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please <a aria-label="Support Rodney Lab via Buy me a Coffee" href="https://rodneylab.com/giving/">consider supporting me through Buy me a Coffee</a>.

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via <a aria-label="D M me on Twitter" href="https://twitter.com/messages/compose?recipient_id=1323579817258831875">@askRodney</a> on Twitter and also <a aria-label="Contact Rodney Lab via Telegram" href="https://t.me/askRodney">askRodney on Telegram</a>. Also, see <a aria-label="Get in touch with Rodney Lab" href="https://rodneylab.com/contact">further ways to get in touch with Rodney Lab</a>. I post regularly on <a aria-label="See posts on svelte kit" href="https://rodneylab.com/tags/sveltekit/">SvelteKit</a> as well as other topics. Also <a aria-label="Subscribe to the Rodney Lab newsletter" href="https://rodneylab.com/about/#newsletter">subscribe to the newsletter to keep up-to-date</a> with our latest projects.