Vue components css background-image path error
Asked Answered
A

4

21

output

    output: {
        path: config.build.assetsRoot,
        publicPath: process.env.NODE_ENV === 'production' ? 
        config.build.assetsPublicPath : config.dev.assetsPublicPath,
        filename: '[name].js'
    }

base

  build: {
    env: require('./prod.env'),
    index: path.resolve(__dirname, '../dist/index.html'),
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: './',
    productionSourceMap: false,
    productionGzip: false,
    productionGzipExtensions: ['js', 'css']
  },

after build,the index pages work normal, css background-image path like this

background: url(./static/img/bg_certificate.c5cad1e.png) no-repeat 50%;

but the component css background-image path error, like this

background: url(static/img/btn_my.b9186cc.png) no-repeat 50%;

It's look like the path lose "./",

Aeriela answered 11/3, 2017 at 16:22 Comment(2)
I am having similar issue. When I set build:{ assetsPublicPath: './'} my dist css file still build to "url(static/img"Outfight
Are you using the css-loader plugin?Trove
H
10

I also come by this issue when I tried using styles in component of Vue 3. I solved it by using the following syntax.

background-image: url('~@/assets/image.png');
Heterocyclic answered 8/9, 2021 at 12:54 Comment(2)
Should be the accepted answer.Layfield
"You cannot use the @ alias as Webpack cannot understand this alias inside the <style></style> tags." - quote from another commentSpirometer
B
9

Instead of absolute path, You should give the relative path from the current file location with webpack in .vue file, something like:

background: url(../../static/img/btn_my.b9186cc.png) no-repeat 50%;
Boorman answered 11/3, 2017 at 16:24 Comment(2)
I've been running "npm run build" with different assetsPublicPath: values and for some reason "./" will not create in my css a relative path in the background-image: url(./static/img) like so...only url(static/img)Outfight
@AkinHwan possible to create a basic template of your code having this issue and put that on Github for us to play and fix this?Boorman
P
6

What about setting:

build: {
  ...
  assetsSubDirectory: '',
  assetsPublicPath: '/static/',
  ...
}

and so:

background: url(/static/img/btn_my.b9186cc.png) no-repeat 50%;

Working with relative paths is, in general lines, a nightmare.

Philipphilipa answered 1/5, 2018 at 9:17 Comment(0)
S
4
:style="{ backgroundImage: 'url(\'' + require('@/assets/bg3.jpg') + '\')' }

This will be the Best solution for the background image.

Salcedo answered 17/10, 2019 at 15:9 Comment(2)
You mixed some react syntax here... Vue would be something like: :style=" background-image: url(${require('@/assets/bg3.jpg')}) "Intrados
This "require" was the real solution for me, very thanks.Brambly

© 2022 - 2024 — McMap. All rights reserved.