Vue - Vite | Static svg assets
Asked Answered
P

3

5

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

<img class="..." 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.

Propjet answered 4/7, 2022 at 8:27 Comment(0)
V
10

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', 👈
    }),
  ],
})

demo 1

...or use a url import param:

                             👇
<img src="@/assets/logo.svg?url" />

demo 2

Without vite-svg-loader

If you just want to get the *.svg's URL, you actually don't need vite-svg-loader, as that's a built-in feature. Removing vite-svg-loader should resolve the issue:

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

export default defineConfig({
  plugins: [
    // svgLoader() ⛔️ delete
  ],
})

demo 3

Vann answered 5/7, 2022 at 2:8 Comment(0)
M
3

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

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

<img class="..." :src="mainBanner" alt="Background">
Multitudinous answered 4/7, 2022 at 8:32 Comment(0)
A
0

I had a similar issue, I wanted to import many banners, like main-banner1.svg, main-banner2.svg, and so on, so I tried

<img :src="`/src/assets/images/bg/main-banner${bannerId}.svg`" alt="Background">

but I had a problem when trying to re-use the banner with another view.

My solution was to move the svg file to the public folder and use the path as:

<img :src="`/main-banner${bannerId}.svg`" alt="Background">

Note that this also prevents Vite from adding hashing to the file names.




Note: It is also possible to organize everything in sub-folders in the public folder to use the original path.

<img :src="`/src/assets/images/bg/main-banner${bannerId}.svg`" alt="Background">
Abreu answered 21/12, 2022 at 17:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.