Francisco Martin
Francisco Martin

Reputation: 627

How to use asset URLs in style binding with Vite

I want to show a background image from my assets folder. When I use an image tag, the image is shown properly, so the image is well placed, but throws a 404 when I use the background-image style. Any idea about what is happening?. I am using Vue 3 with TypeScript and Vite 2.

This does not resolve the URL:

<div style="background-image: url(./assets/img/header.png)"
></div>

But this does:

<img src="./assets/img/header.png" alt="Header" />

Upvotes: 19

Views: 31108

Answers (2)

tony19
tony19

Reputation: 138226

The URL needs to be resolved with import in <script>. @vue/compiler-sfc does not automatically resolve the URLs in <div>.style, but it does for <img>.src, which is why your second example works correctly.

Solution

Use the import keyword in a <script> block to expose the resolved image URL to the template:

<script setup>
import imagePath from '@/assets/logo.svg'
</script>

<template>
  <div class="logo" :style="{ backgroundImage: `url(${imagePath})` }"></div>
</template>

<style>
.logo {
  height: 400px;
  width: 400px;
}
</style>

demo

Upvotes: 26

Sagar Davara
Sagar Davara

Reputation: 454

This is due to vite can't handle alias by default, so we need to set up an alias in vite config file.

there is no need to setup the import image in script tag.

just put the below code in vite.config.js file

import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "/src"),
      "~@": path.resolve(__dirname, "/src"),
    },
  },
});

Upvotes: 6

Related Questions