0

I try to use webpack sass-loader to load a .scss file which contains background images. Part of the .scss is like

.clouds_two {
  background: url(require("../../../images/cloud_two.png"));   //no error, just not display
  //background: url("../../../images/cloud_two.png");     // 404 error
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 300%;
  -webkit-animation: cloud_two 75s linear infinite;
  -moz-animation: cloud_two 75s linear infinite;
  -o-animation: cloud_two 75s linear infinite;
  -webkit-transform: translate3d(0, 0, 0);
  -moz-transform: translate3d(0, 0, 0);
  -o-transform: translate3d(0, 0, 0)
}

Corresponding loaders in my webpack config file are set as

  {
    test: /\.scss$/,
    exclude: /node_modules/,
    loaders: ['raw-loader', 'sass-loader'] // sass-loader not scss-loader
  },
  {
      test: /\.(png|jpg|gif)$/,
      loader: 'url-loader?limit=8192'
  }, // inline base64 URLs for <=8k images, direct URLs for the rest

My .scss file is in src/app/components/login/ and the image is in src/images/. The webpack output folder is dist which is of same level as src folder.

The problem is when I use background: url(require("../../../images/cloud_two.png"));, there's no error but the background image not showing.

If I use background: url("../../../images/cloud_two.png");, there's a 404 error complaining http://localhost:8080/images/cloud_two.png.

The sass-loader's readme has a Problems with url(...) section, but it can't fix my case.

Bing Lu
  • 3,232
  • 7
  • 30
  • 38
  • The url used should be relative to the sass file. If you inspect the network tab does it actually download the image? – cgatian Jul 21 '16 at 23:33
  • @cgatian Yeah, I use relative url to access the `.png` file. The browser tries to download the file but gets a 404. – Bing Lu Jul 22 '16 at 02:25

1 Answers1

1

I figure it out. In this webpack.common.js file, the CopyWebpackPlugin can copy files and directories into webpack.

new CopyWebpackPlugin([{
  from: 'src/assets',
  to: 'assets'
}]),

The path didn't match my project structure. And after I change it, my .pngs can be copied to webpack. And in my .scss file, background: url("assets/cloud_two.png"); works for me.

Note: the path in url() is relative to the webpack output folder. Eg. my output folder is like

dist
    /assets
        cloud_two.png
    main.bundle.js
    vendor.bundle.js
    polypill.bundle.js
Bing Lu
  • 3,232
  • 7
  • 30
  • 38