cssreactjswebpackwebpack-style-loadersass-loader

background-image URL not loading using Webpack


Basically I am trying to have an image display in the background of a container, but it isn't loading. I have tried various paths as it isn't entirely clear to me what the URL needs to be relative to: the package.json, the webpack.config.js, the React component, or the login.scss I am working in.

I'll provide the directory structure in addition to the webpack.config.js:

/app
    /src
        /assets
            /img
                slide_blue.png
            /scss
                login.scss
        /config
            webpack.config.js
        /react
            /containers
                /authentication
                    signin.js
            index.js // entry point
    package.json

The login.scss is short thus far and the other styles are working:

// logic.scss
@import 'declarations';

.login {
    height: 381px;
    // tried just about every combination of path... this is just the last one I tried
    background-image: url('/src/assets/img/slide_blue.png') !important;

    form {
        padding-top: 75px;
        padding-bottom: -75px;
    }
}

And then finally the webpack.config.js:

var path = require('path');
var webpack = require('webpack');
var BundleTracker = require('webpack-bundle-tracker');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

const VENDOR_LIBS = [
  'axios', 'history', 'lodash', 'prop-types', 'react', 'react-dom', 'react-dropzone', 'react-redux', 'react-router-dom', 'react-router-redux', 'redux', 'redux-form', 'redux-thunk', 'reactstrap'
]

module.exports = {
  context: __dirname,

  entry: {
    app: '../react/index',
    vendor: VENDOR_LIBS
  },

  output: {
      path: path.resolve('./src/assets/bundles/'),
      filename: './js/[name].[chunkhash].js'
  },

  module: {
    rules: [
      { 
        loader: 'babel-loader',
        test: /\.js$/, 
        exclude: /node_modules/, 
        query: {
          presets: ["react", "es2015", "stage-1"]
        }
      },
      {
        test: /\.json$/,
        loader: ['json-loader'] 
      },
      {
        test: /\.scss$/,
        loader: ['style-loader', 'css-loader', 'sass-loader'] 
      },
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader']
        })      
      },   
    ],
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest']
    }),
    new BundleTracker({filename: './src/config/webpack-stats.json'}),
    new ExtractTextPlugin({filename: './css/[name].[hash].css', allChunks: true})
  ],
  resolve: {
    extensions: ['*', '.js', '.jsx', '.json', '.gif', '.png'],
  },
}

What am I missing here that is preventing the background-image: url(...) from displaying?

EDIT

The React component just in case:

    return (
        <div className='login'>
            <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
                {this.renderAlert()}
                <Field 
                    label='Username'
                    name='username'
                    type='username'
                    component={this.renderField} 
                />
                <Field 
                    label='Password' 
                    name='password'
                    type='password' 
                    component={this.renderField} 
                />
                <div className='row'>
                    <div className='col-sm-2'>
                        <button type='submit' className='btn btn-primary'>Sign in</button>
                    </div>
                    <div className='col-sm-10 pull-right'>
                        <ul className='pull-right signin'>
                            <li><Link to='/auth/username'>Username Recovery</Link></li>                
                            <li><Link to='/auth/password'>Password Reset</Link></li>                                
                            <br />
                            <li><Link to='/auth/new_account'>New Accounts</Link></li>
                        </ul>
                    </div>
                </div>
            </form>
        </div>
    );

EDIT 2

I added the following to webpack.config.json:

  {
    test: /\.png|jpg$/,
    include: path.join(__dirname, 'assets/img'),
    loader: ['file-loader'] 
  },

And updated the background-image: url(...) to be relative to my entry point index.js:

background-image: url('/../assets/img/slide_blue.png');

Doesn't produce an error and doesn't load the image.

Tried the following and it produces the corresponding error:

background-image: url('../assets/img/slide_blue.png');
Module not found: Error: Can't resolve '../assets/img/slide_blue.png' in '/mnt/c/dev/current/app/src/assets/scss'

Also gave this a shot which produces the corresponding error:

background-image: url('../../assets/img/slide_blue.png');
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.

So still not sure what is up. I have been loading images into my components doing the following, which has me questioning if it is even right (but that is another question):

import logo from '!!url-loader!../../../assets/img/logo.png';

Solution

  • You need a file-loader to handle the image files:

    { 
        test: /\.(png|jpg)$/,
        include: path.join(__dirname, 'assets/img'),
        loader: 'file-loader' 
     }
    

    And the path will be relative to your entry point.