For anyone looking to refer images from template, You can refer images directly using '@'
Example:
<img src="@/assets/images/home.png"/>
In a Vue regular setup, /assets
is not served.
The images become src="data:image/png;base64,iVBORw0K...YII="
strings, instead.
require()
To get the images from JS code, use require('../assets.myImage.png')
. The path must be relative (see below).
So your code would be:
var icon = L.icon({
iconUrl: require('./assets/img.png'), // was iconUrl: './assets/img.png',
// iconUrl: require('@/assets/img.png'), // use @ as alternative, depending on the path
// ...
});
For example, say you have the following folder structure:
- src
+- assets
- myImage.png
+- components
- MyComponent.vue
If you want to reference the image in MyComponent.vue
, the path sould be ../assets/myImage.png
Here's a DEMO CODESANDBOX showing it in action.
Adding some good practices and safity to @acdcjunior's answer, to use @
instead of ./
In JavaScript
require("@/assets/images/user-img-placeholder.png")
In JSX Template
<img src="@/assets/images/user-img-placeholder.png"/>
using @
points to the src
directory.
using ~
points to the project root, which makes it easier to access the node_modules
and other root level resources
In order for Webpack to return the correct asset paths, you need to use require('./relative/path/to/file.jpg'), which will get processed by file-loader and returns the resolved URL.
computed: {
iconUrl () {
return require('./assets/img.png')
// The path could be '../assets/img.png', etc., which depends on where your vue file is
}
}
See VueJS templates - Handling Static Assets
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With