Ricey
Ricey

Reputation: 41

Vue 3 + Vite image URL becomes undefined after build

I encountered a bug where I dynamically generated a URL from props for image import in my Vue 3 component and it becomes undefined after build

const imagePath = computed(() => { return new URL(`../assets/${props.imgPath}.png`,
    import.meta.url).href

<img :src="imagePath" />

Only two out of the many images are undefined after build which makes it very hard to pin down the problem

I tried messing around with vite.config.ts, particularly assetInlineLimit under the build section but so far nothing works

Upvotes: 4

Views: 10249

Answers (4)

Yash Jain YJ
Yash Jain YJ

Reputation: 1

I Found one simple solution to use this with the help of core javascript concept.

To access env. variable you need to define with VITE_ prefix (for ex: VITE_APP_VERSION ) And then in vite.config.ts define config

define: {
'process.env': env,
global: 'window'
},

then in any util file you can directly use process.env.VITE_APP_VERSION

For accessing images in the assets folder, the traditional require() method is not supported in Vite. Instead, you should use the import.meta.url with the URL class. However, a more efficient approach is to create a utility file for managing images. This allows you to import images directly and use them throughout your project.

import imageName from '@/assets/your_image_name';
export class ImageUtil {
static imageName
}

and then use in any file like this

import { ImageUtil } from './ImageUtil';
const myImage = ImageUtil.imageName;

Hope it is helpful

Upvotes: 0

Cerceis
Cerceis

Reputation: 850

I am a bit late. But for anyone still having this problem,

Similar to OP, this will not work.
It will return undefined. (http://localhost:5173/src/assets/icons/undefined)

const src = computed(() => {
    return new URL(`@/assets/icons/${props.src}`, import.meta.url);
});

Simply move the template literals into a variable.
And everything should work now.

const src = computed(() => {
    const path = new URL('@/assets/icons/', import.meta.url);
    return `${path}/${props.src}`
});

Apparently, new URL does not work well with template literals.
there's multiple bug report on this, and might be fixed in the future.
I am using vite 4.0 as of writing this post.

Upvotes: 8

Bahaa Samoudi
Bahaa Samoudi

Reputation: 173

I faced same problem, solution in my case, the image name must be like props name because it's case sensitive so I changed image name from "myimage.png" to "myiMage.png"

Upvotes: 0

brenzy
brenzy

Reputation: 1986

I was having the same issue and found that you need to set the build target to 'es2020' since import.meta.url is not defined in the default build target. There is a small note at the bottom of this page: https://vitejs.dev/guide/assets.html

Upvotes: 2

Related Questions