Home > Net >  vite rollup css background-img with reactive url image missing
vite rollup css background-img with reactive url image missing

Time:09-15

I have a vue3-vite project with a background missing issue

There is my vue project directory tree:

src/assert/pic1.png

src/components/pages/Page1/Page1.vue

I use a css background-img tag in Page1.vue : background-image: url("src/assert/pic1.png")

This setting in dev env it's worked, the request url is http://.../src/assert/pic1.png

But in test env the request url turn to http://.../src/assets/src/assert/pic1.png

I think maybe is sth wrong in roll up setting, but I don't know how to fix it...

CodePudding user response:

found solution in https://vitejs.dev/guide/assets.html

  1. Import pic path as backgroundUrl variable import backgroundUrl from "~/assert/pic1.png"

  2. Set as variable in 'script' tag const backgroundStyle = `background-image:url(${backgroundUrl})`

  3. In target document element set reactive style <div :style=backgroundStyle>

CodePudding user response:

Add resolve.alias in vite.config by following.

https://vitejs.dev/config/shared-options.html#resolve-alias

vite.config.js

import path from "path";

// ...
resolve: {
  alias: {
    "@": path.resolve(__dirname, "./src")
  }
}

Page1.vue

background-image: url("@/assert/pic1.png")
  • Related