Home > database >  Vue - Vite | Static svg assets
Vue - Vite | Static svg assets

Time:07-05

In my Vue vite app, I am trying to use svg file as src attribute in html element.

<img  src="/src/assets/images/bg/main-banner.svg" alt="Background">

In development, it works as expected. In production, the src attribute of the image is [object Object]. I tried every approach from Vite documentation , but none of these could fix the issue. I am using vite-svg-loader, so I can use svg files as Vue Components. Could this be somehow related to the issue?

Thank you.

CodePudding user response:

Try to import it as module then bind it to the src attribute :

import mainBanner "~/assets/images/bg/main-banner.svg"

<img  :src="mainBanner" alt="Background">

CodePudding user response:

With vite-svg-loader

vite-svg-loader causes *.svg to resolve as Vue components by default, which would be converted into a string for the <img>.src attribute, resulting in [object Object].

To load the *.svg as a URL instead, you can either configure the loader to import the url by default:

// vite.config.js
import { defineConfig } from 'vite'
import svgLoader from 'vite-svg-loader'

export default defineConfig({
  plugins: [
    svgLoader({
      defaultImport: 'url',            
  • Related