vue cli 3 – use background image in style tag

iamrobin. picture iamrobin. · Aug 12, 2018 · Viewed 35.9k times · Source

I want to use a svg image from my assets folder in one of my components as a background-image. Here is an example of my component:

<template>
  <div class="container"></div>
</template>

<script>
export default {
  name: 'component'
}
</script>

<style scoped lang="scss">
.container {
  height: 40px;
  width: 40px;
  background-image: url('@/assets/image.svg');
}
</style>

But the image doesn't show. The Path is correct. Where is my mistake? Thanks for your help.

Answer

Ragaar picture Ragaar · Jan 3, 2019

As Max Martynov, highlighted in the comments, you should use url('~@/assets/image.svg').

 

Webpack has some specific rules when resolving assets[1].

In order to resolve an alias (@), as you are using, it is mandatory webpack handles the request as a module request. Using the prefix ~ enforces webpack to treat the request as a module request, similar to require('some-module/image.svg').

 

References

  1. https://vuejs-templates.github.io/webpack/static.html#asset-resolving-rules