Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I load image(s) used in sass stylesheet in webpack?

I am using Webpack to bundle my modules and using sass for styling purpose in a react based application.

Using a seperate style-sheet I am setting the background-image of a component and loaded that style-sheet in index.js. All the styles in style-sheet gets applied to that component except background image.

Here is my sample style-sheet

$bg-img: url('/img/bg.jpg');

.show {
    position: relative;
    background: $black $bg-img center center;
    width: 100%;
    height: 100%;
    background-size: cover;
    overflow: hidden;
}

One way to solve that problem would be explicitly require the image and then create inline style for react components.

img1 = document.createElement("img");
img1.src = require("./image.png");

But I want to load all the images from my image folder as soon as my style-sheet loads not by requiring each image separately.

My webpack config file is

module.exports = {
  devtool: 'source-map',
  entry: {
    main: [
      'webpack-dev-server/client?http://localhost:8080',
      'webpack/hot/only-dev-server',
      './src/index.js'
    ]
  },
  output: {
    path: path.join(__dirname, 'public'),
    publicPath: '/public/',
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
   loaders: [
      {
        test: /\.jsx?$/,
        include: path.join(__dirname, 'src'),
        loader: 'react-hot!babel'
      },
      {
        test: /\.scss$/,
        include: path.join(__dirname, 'sass'),
        loaders: ["style", "css?sourceMap", "sass?sourceMap"]
      },
      { 
        test: /\.(png|jpg)$/,
        include: path.join(__dirname, 'img'),
        loader: 'url-loader?limit=10000' 
     } // inline base64 URLs for <=10k images, direct URLs for the rest
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
};

I may be missing some trivial points. Any help is appreciated.

like image 961
WitVault Avatar asked Feb 10 '16 20:02

WitVault


1 Answers

Ahh.... After a long hours of debugging I have finally found the issue. It was my foolishness because of which I struggled. I wanted to delete this question but thought that it would help new comers like me when the stuck to similar issues.

Problem was here

loader: 'url-loader?limit=10000'

I was setting the limit to file size of 10kb without really knowing what it does. And the image which I was loading was of size 21kb ! This happens when you copy some else webpack config files :) Sign of javascript fatigue !

like image 166
WitVault Avatar answered Sep 24 '22 12:09

WitVault