carlhandy
carlhandy

Reputation: 315

Load static assets with vue-cli 3.x

I have a vue-cli 3 project setup with the following directory structure:

enter image description here

All static assets are loaded in the public directory and are compiled and built successfully on localhost.

As seen in the image below, guyana-live-logo.png, slide-1.jpg and 970x250-ad.png are all loaded successfully, however, only the logo and the ad image appears in the browser.

enter image description here

What I've tried

  1. Changing the way the image is referenced.

Original - which works for almost all other images

<img src="/img/slide-1.jpg"/>

Test 0 - this loaded the image with a hash appended (slide-1.1b0ahsa.jpg) but it still did not appear in the browser

<img src="../../../public/img/slides/slide-1.jpg">

Test 1 - using v-bind

<img :src="'/img/slide-1.jpg'"/>
  1. Moving the image inside the src directory and the component sub-directory both of which proved futile.

  2. Updating vue-loader

  3. Building for production and serving only the /dist folder

Key notes

Upvotes: 0

Views: 2338

Answers (1)

now_world
now_world

Reputation: 1096

The images will need to be in the same directory or a child directory of the file in which you're trying to access them (i.e. in the Components directory).

Can you also try to access the image via its URL <img src="http://localhost:8080/img/guyana-live-logo.png" />?

This should work, but you may not want to use it this way.

Another possibility you might be able to use is doing this:

<script>
import image from './img/slide-1.jpg'
...

Then in Vue data:

  data() {
    return {
      img: image,
    };

  },

Then in your HTML:

<img :src="image"/>

This solves issues when trying to access images when building with Parcel Bundler

Upvotes: 1

Related Questions