Search code examples
reactjssasswebpackwebpack-dev-serverwebpack-style-loader

require is working jsx file but url() resolve is not wroking in sass file - webpack


I am facing this strange issue with Webpack. After spending hours couldn't find solution.

In my jsx file when I a try to set image source via this

let img = require('../../../img/imgN.png');

It is working perfectly but when I try to set the background image using scss via

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

Image is not getting loading by webpack.

This is my webpack file

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=30000'
     } // inline base64 URLs for <=30k images, direct URLs for the rest
    ]
  },
  resolve: {
    extensions: ['', '.js', '.jsx']
  },
  devServer: {
    historyApiFallback: true,
    contentBase: './'
  }
}

Solution

  • Problem was occurring because of using sourceMap with style-loader.

    There is some issue on github for the same problem.

    Solution:

    1 . While source-maps is enabled

    Style-loader uses a Blob, so it requires absolute urls to work.

    Changed publicPath: '/public/', to

    publicPath: 'http://localhost:8080/public/',
    

    It worked.

    1. Without source-maps Just remove source map from style loaders.

    Now style-loader will use an inline style tag, so there is no problem.

    {
            test: /\.scss$/,
            include: path.join(__dirname, 'sass'),
            loaders: ["style", "css", "sass"]
    },