Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use images in css with Webpack

I am making a React w/ Webpack setup and am struggling to do what seems like should be a simple task. I want webpack to include images, and minimize them like I with gulp but I can't figure it out. I just want to be able to link an image in my css like so:

/* ./src/img/background.jpg */  body { background: url('./img/background.jpg'); } 

I have all of my css/js/img folders inside a src folder. Webpack outputs to a dist folder, but I can't figure out how to get images there.

Here is my webpack setup:

 var path = require('path');  var webpack = require('webpack');  var HtmlWebpackPlugin = require('html-webpack-plugin');   module.exports = {   devtool: 'cheap-eval-source-map',   entry: [    'webpack-dev-server/client?http://localhost:8080',    'webpack/hot/dev-server',    './src/index.js'   ],   output: {   path: path.join(__dirname, 'dist'),   //  publicPath: './dist',   filename: 'bundle.js'   },   plugins: [   new webpack.HotModuleReplacementPlugin(),   new HtmlWebpackPlugin({   template: './src/index.html'    })   ],   module: {   loaders: [{    exclude: /node_modules/,    test: /\.js?$/,    loader: 'babel'    }, {   test: /\.scss$/,   loader: 'style!css!sass'     }, {   test: /\.(png|jpg)$/,   loader: 'file-loader'   }]  },   devServer: {   historyApiFallback: true,   contentBase: './dist',   hot: true   } }; 
like image 711
user3737841 Avatar asked Feb 12 '16 18:02

user3737841


People also ask

How do I load a CSS file into webpack?

To be able to use CSS in your webpack app, you need to set up a new loader. Out-of-the-box, webpack only understands Javascript and JSON. With a loader, you can translate another type of file to a format that webpack understands and can work with. There are many webpack loaders and each loader has a specific purpose.

How do I bundle CSS with webpack?

By default, Webpack will inline your CSS as Javascript tags that injects the CSS into the page. This sounds strange but it lets you do hot reloading in development. In production you extract them to a file using the ExtractTextPlugin, and require it with a normal link tag.


1 Answers

I was stuck with similar issue and found that you can use url-loader to resolve "url()" statements in your CSS as any other require or import statements.

To install it:

npm install url-loader --save-dev

It will install the loader that can convert resolved paths as BASE64 strings.

In your webpack config file use url-loader in loaders

{   test: /\.(png|jpg)$/,   loader: 'url-loader' } 

Also make sure that you are specifying your public path correctly and path of images you are trying to load.

like image 71
WitVault Avatar answered Sep 22 '22 17:09

WitVault