Webpacker: Background Image Url not working in scss files

Created on 19 Oct 2019  路  3Comments  路  Source: rails/webpacker

Webpacker 4.0.7

Folder Structure

  • javascript

    • main-app



      • images





        • asset2.png





      • styles


        welcome.scss



    • packs



      • pages





        • welcome







          • index.scss










# view welcome.html.erb
<%= javascript_pack_tag 'pages/welcome/index' %>
// packs/welcome/index.scss
@import "./../../../main-app/styles/welcome";
// main-app/styles/welcome.scss
.culture {
  background-image: url('../images/asset2.png');
}

The error

Module not found: 
Error: Can't resolve '../images/asset2.png' 
in '/app/javascript/packs/pages/welcome'

The manifest.json

{"media/main-app/images/asset2.png": "/packs/media/main-app/images/asset2-7040fa15ac8a960a3b9fc3d7f8939a64.png"}

How do I fix?

// put the path the manifest.json 
.culture {
  background-image: url('media/main-app/images/asset2.png');
}

Do you know why is happening this ?

file loaders

Most helpful comment

I was able to access it only via relative path, credits here.

For your case it should be

# main-app/styles/welcome.scss
background-image: url('../images/asset2.png');

I tried deploying to heroku in production environment and it works as well. The url gets transformed to /packs/media/<my_pack_images_folder>/filename-2da71b64b3j2b.jpg

Did not use any extra loaders in config/webpack/environment.js, just the default.

All 3 comments

Try:

background-image: url('media/main-app/images/asset2.png');
馃憞
background-image: url('~media/main-app/images/asset2.png');

Ref: https://github.com/webpack-contrib/css-loader/issues/256#issuecomment-283409647

I was able to access it only via relative path, credits here.

For your case it should be

# main-app/styles/welcome.scss
background-image: url('../images/asset2.png');

I tried deploying to heroku in production environment and it works as well. The url gets transformed to /packs/media/<my_pack_images_folder>/filename-2da71b64b3j2b.jpg

Did not use any extra loaders in config/webpack/environment.js, just the default.

For me worked without having to use relative paths, like this:

background-image: url('~images/asset2.png');

Was this page helpful?
0 / 5 - 0 ratings

Related issues

FrankFang picture FrankFang  路  3Comments

itay-grudev picture itay-grudev  路  3Comments

amandapouget picture amandapouget  路  3Comments

ilrock picture ilrock  路  3Comments

ytbryan picture ytbryan  路  3Comments