Vue Cli Webpack background url path issue Vue Cli Webpack background url path issue vue.js vue.js

Vue Cli Webpack background url path issue


I managed to replicate your problem with the following steps:

Assuming the following directory:

root/  dist/  src/    assets/      |--box.jpg    components/      |--home.vue

And home.vue:

<template>  <div class="foo">  </div></template><script>  export default {  }</script> <style>  .foo {    background: url('../assets/box.jpg')  }</style>

After building the application and save the files in the dist folder, everything works if I serve the built files using this command inside dist folder (I use lite-server for simplicity):

lite-server index.html

However, if I go back to the root folder and try to do the same:

lite-server dist/index.html

I will encounter the same problem as you.

How I usually get around this is by importing the image first and then using it with inline style:

<template>  <div v-bind:style= "{ 'background-image': 'url(' + box + ')' }">    Placeholder  </div></template><script>  // @ is an alias to /src  import box from '@/assets/box.jpg';  export default {    data() {      return { box };    }  }</script>

Also check out the following discussions:


depends on where your root set, you could try background: url('~/assets/img/box.jpg') or background: url('~/src/assets/img/box.jpg'),
one of them should work


Try the url prefix of '~@/'

background-image: url('~@/assets/box.jpg');