I have a file named Test.vue and inside this file I have an img
tag:
<img src="../../img/map.jpg" alt="Map" />
This works fine and after running npm run build
everything will be generated successfully and image will be displayed.
Now, I want to get rid of those ../
in my path because first of all it looks ugly and second of all sometimes in some other files I even have to provide many more ../
in my path and of course it gets even more ugly.
The Problem is, as soon as we try to use a method or anything else inside our src
attribute, it’s not going to work anymore
<img :src="someMethod('map.jpg')" alt="Map" />
// someMethod('map.jpg') returns exactly the same string : '../../img/map.jpg'
In this case browser displays a 404 not found error in console and it’s looking for 'localhost:8000/img/map.jpg'
(localhost:8000
is my root address) and of course the path is wrong and there is no image in this path.
In order to understand the problem better, take a look at following examples :
<img src="../../img/map.jpg" alt="Map" /> // Works fine
<img :src="'../../img/map.jpg'" alt="Map" /> // Doesn't Work
So, The conclusion is if you write your path without attribute binding it works, and as soon as you use :src
instead of src
it’s not gonna work.
My question is, how can I read paths from a function and compile it successfully?
I am using default configs for Laravel Projects using Inertia, VueJS & Vite.
Here is my scripts section in package.json
"scripts": {
"dev": "vite",
"build": "vite build && vite build --ssr && vite build && vite build --ssr --ssr"
},
By the way, this is my folder structure, if you like to know:
resources
|____ img
| |____ map.jpg
|____ js
| |____ Pages
| |_____ Test.vue
|
|____ css // its content (not important in this example)
|____ views // its content (not important in this example)
2
Answers
Why don’t you use ‘@’ to import resource ,like src="@/img/map.jpg",you just need add a property in your vite.config.js
This is the correct way to bind a relative image path with Vite
Vite documentation
Alternatively, use absolute path