2

I'm trying to show a dynamically imported image, but it's not working with the error

'Cannot find module'

This is my component

<template>
      <div class="footer">
        <div v-for="footerItem in getters" :key="footerItem.id">
          <img :src="methods.requireImage(footerItem.icon)" alt="">
        </div>
      </div>
    </template>

<script lang="ts">
import { defineComponent } from 'vue'
import { useStore } from '@/store'
import { requireImage } from '@/modules/images'

export default defineComponent({
  name: 'Footer',
  setup () {
    const store = useStore()
    const methods = {
      requireImage
    }

    return {
      getters: store.getters.getFooterItems,
      methods
    }
  }
})
</script>

And this is module

export const requireImage = async (link: string) => {
  // return require(link)
  const image = await import(link)
  return image
  // const images = require.context('../assets', false)
  // return images('color-circle.svg')
}

Commented out code not working

1 Answer 1

5

If you pass the full path to require in a variable, Webpack can't load the image. This is roughly because it's a build-time tool, and the path is created at runtime. If you hard-code at least some of the path though, that will be sufficient:

export const requireImage = link => {
  return require(`@/assets/${link}`);
}

Note: Removed the unnecessary async or the return value would be a promise

Your variable footerItem.icon should just contain the filename color-circle.svg now that some of the path is hard-coded in the call to require. With that done, you can use the method in the template as you wanted:

<img :src="methods.requireImage(footerItem.icon)" alt="">

Be aware that at the moment your wrapper method is unnecessary because you could get the same result from:

<img :src="require(`@/assets/${footerItem.icon}`)">
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! After a zillion tries I made it work... I'm not sure why lint is not throwing an error when I import the function but it does when I try to use require directly...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.