After the build process, image URLs in Vue 3 + Vite are returning as undefined

Encountered an issue where the URL generated dynamically from props for image import in my Vue 3 component became undefined post-build

  • Check out the script used to generate the URL and the tag in the Vue Component below
const imagePath = computed(() => { return new URL(`../assets/${props.imgPath}.png`,
    import.meta.url).href

<img :src="imagePath" />
  • Observed Undefined URL after build
    <img class="img" src="http://localhost:4173/undefined />

Only a couple of images turn out undefined after the build, making it challenging to identify the root cause of the problem

Tried adjusting vite.config.ts, specifically assetInlineLimit under the build section, but haven't had any success yet

Answer №1

I'm a little behind schedule, but if anyone is still facing this issue,

Just like the original poster (OP), this solution won't solve the problem.
It will just give you undefined. (http://localhost:5173/src/assets/icons/undefined)

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

All you need to do is store the template literals in a variable.
Then everything should function correctly.

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

Apparently, new URL doesn't play nice with template literals.
There are several bug reports about this, and it may be fixed in the future.
I'm currently using vite 4.0 at the time of writing this response.

Answer №2

After encountering a similar problem, I discovered that adjusting the build target to 'es2020' is necessary as import.meta.url is not supported in the default build target. For more information, you can refer to the bottom of this page: https://vitejs.dev/guide/assets.html

Answer №3

Dealing with a similar issue, I discovered that the problem lied in the naming convention of the image file. It appears that the image name must match the props name exactly due to case sensitivity. Therefore, I resolved the issue by renaming the image from "myimage.png" to "myiMage.png"

Answer №4

After delving into core JavaScript principles, I uncovered a straightforward solution for utilizing this method.

To tap into environment variables, you must preface them with the VITE_ prefix (e.g., VITE_APP_VERSION). Then in vite.config.ts, configure it as follows:

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

Subsequently, within any utility file, you can directly access process.env.VITE_APP_VERSION.

As for accessing images within the assets directory, traditional methods like require() are not supported in Vite. Instead, leverage import.meta.url with the URL class. Alternatively, create an image utility file for streamlined image management and seamless project-wide usage.

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

Then, simply reference it in any file as demonstrated below:

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

I trust you find these insights beneficial!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Most effective method for converting a table of data to TypeScript

Searching for an effective method to map a table of enum (or interface) data to the correct location. https://i.sstatic.net/5hF2q.png For instance, Smoke Sensor - Push Button can only be linked to SS - PI SYMBOL and Smoke Sensor - PushButton can only be ...

What is the best method for uploading and saving a file using AngularJS and ExpressJS together?

I am using a library for AngularJS called angular-file-upload. Despite successfully setting it up and getting image uploads to work, I am facing an issue with passing the file to the server side (express js). Jade: input.form-input(ng-model="userAvatarFi ...

Array-based input validation

Is there a way to validate an input field against a list of strings in an array without using custom directives or patterns? For example, if the array contains town, city, and house, then typing any of those words should result in a validation failure. An ...

Determine the total columns present within a table row

I created a table that looks like this: <table id="table1"> <tr> <td><input type="text" value="" /></td> <td><input type="text" value="" /></td> <td><input type="text" value="" /></td> ...

How can Typescript be leveraged to enforce a generic constraint on an interface?

I have defined 2 interface declarations : interface IStore { } interface AnotherInterface { a: number; } Also, there are 2 classes which implement each interface: class StoreImplementation implements IStore { } class AnotherImplementation implement ...

Three.js - Rendering issues persist after updating geometry

I've encountered a puzzling issue. I have created a THREE.Line object with a material and geometry. The init method adds 2 vertices to the geometry, places the Line in the scene, and the line renders correctly. However, there's an event listener ...

Continuously receiving unhandled promise rejection errors despite implementing a try-catch block

Every time I run my code, I encounter the following issue: An UnhandledPromiseRejectionWarning is being thrown, indicating that a promise rejection was not properly handled. This can happen if you throw an error inside an async function without a catch bl ...

Dealing with unexpected modifications in a React class component

In short, I need to adjust the data in my class component before sending it to the server to match the API request format. To achieve this, I created a method called transformData within my class component which transforms the data extracted from the state ...

Solving an object in ui-router state using ui-sref

Dealing with a large JSON object in an Angular controller and wanting to pass it to the controller of a template that will be displayed in a ui-view. I am aware that parameters can be passed to states using ui-sref, but I do not want this object to be visi ...

Updating the state within a component while specifically modifying the second item within a list

Currently in the process of constructing a battleShip game using React. Within my component, I have a state structured as follows: each coordinate is paired with a list containing two statuses - 'empty' indicating the absence of a ship ('bu ...

Tips for properly including my Dialog Flow access token in the environment file within the Angular CLI

I am currently in the process of creating a bot using angular cli and integrating dialog flow's API. The issue I am facing is that when I perform debugging in Chrome, I encounter the following error logs: ApiAiClientConfigurationError columnNumber: ...

Using Conditional Rendering and ReactCSSTransitionGroup for Dynamic Animations

I have developed a small application that displays different components based on a Redux state. I am trying to add a "fade" animation when one of the components renders, but unfortunately, it is not working as expected. Here is my current setup: content.j ...

Encountering an issue when using npm to add a forked repository as a required package

While attempting to install my fork of a repository, I encountered the error message "Can't install github:<repo>: Missing package name." The original repository can be accessed here, but the specific section I am modifying in my fork is located ...

Utilize zimJS within an Angular 4 application written in Typescript

After extensive searching, I have come up empty-handed in my quest to find the answer. There are no modules available for zimjs, only for createjs, but I require the entire package. I have exhausted all resources and still cannot find a solution. I am ke ...

Sending a file with Node.js without redirecting to a different page

I've recently been exploring tutorials on file uploads using Node.js and was able to successfully upload files following the instructions provided at https://www.geeksforgeeks.org/file-uploading-in-node-js/. However, I noticed that every time a file i ...

Exclusive pair of vertices within a network

I am working with a diagram that includes nodes A, B, C and several edges connecting these nodes. How can I extract the distinct pairs (A, B), (A, C), (B, C)? One potential method is: visited = []; for item1 in nodes: for item2 in nodes: if (item ...

Utilizing ThreeJS to Implement Targeted Bloom Effects on Individual Object Components with Emission Mapping

I have a project where I need to showcase 3D objects with small LED lights that should emit a glow effect. I've attempted to use UnrealBloom, but the issue is that it affects the entire scene and makes everything look blurry, not just the parts with t ...

Utilizing Vue to tie assets to personalized attributes

When working with Vue3, what is the correct way to bind a custom HTML attribute to an asset? The current method being used does not seem to be effective. <template> <span :data-imageurl="logo" /> </template> <script setu ...

The jQuery function does not accurately represent the class change made by another event

When hovering over a class anchor, an alert will display the title value. If the anchor has a nohover class, a nopop class will be added to prevent the alert. This ensures that the alert only appears when hovering over the class anchor without the nopop cl ...

``Creating apertures in a rectangular shape using three.js: A step-by-step guide

I've been attempting to create two holes in a simple rectangle using three.js, but I'm facing an issue where the holes aren't showing up correctly with a 3D effect. Below is my current approach: const modelContainer = document.getElementByI ...