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:
- Github: background image best practice
- Github: html image src require not respecting webpack aliases?
- Github: vue-loader not processing images in dynamic component
- Github: problem with background url
- StackOverflow: Vue.js data-bind style backgroundImage not working
- StackOverflow: webpack css-loader not finding images within url() reference in an external stylesheet