Images and Fonts
The CSS loader treats url
statements in stylesheets similar to any other require
statement -- it attempts to resolve the path. With that in mind, we need to tell webpack how to handle images and fonts by adding loaders for them to our webpack config.
File and URL Loaders
The file loader is used to take a file in your source directory and copy it to the output directory as a file.
The url loader is used to take a file in your source directory and inline it as a data URL. This can be very useful for small files, because the overhead of an HTTP request to fetch the resource is not worth the few kilobytes the data URL will add to your stylesheet.
These two loaders can be used in combination to smartly inline smaller files as data URI's while leaving the larger files as files on disk.
Here's some configuration to handle images and fonts:
module.exports = {
output: {
path: path.join(__dirname, 'build'),
filename: '[name].js'
},
entry: {
app: './js/app.js'
},
module: {
loaders: [
// Export CSS files to a file in the output directory
{test: /\.css$/, loader: ExtractTextPlugin.extract('css-loader')},
// Image URL config. Generate data URI's for images smaller than 10,000 bytes
{test: /\.(png|gif|jpe?g|svg)$/i, loader: 'url?limit=10000'},
// Image file config. Generate hashed file names to make them easy to cache.
{
test: /\.(png|gif|jpe?g|svg)$/i,
loader: 'file?hash=sha512&digest=hex&name=[path][name]-[hash].[ext]'
},
// Inline font files smaller than 10000 bytes
{ test: /\.(woff2?|ttf|eot|svg)$/, loader: 'url?limit=10000' },
// File loader for fonts larger than 10000 bytes.
{ test: /\.(woff2?|ttf|eot|svg)$/, loader: 'file?name=[name].[ext]' }
]
},
plugins: [
new ExtractTextPlugin("[name].css", {allChunks: true})
]
}
Here's app.js
:
require('../css/app.css');
And app.css
:
.hero {
background-image: url("../img/image.png");
background-repeat: no-repeat;
}
Which becomes this when compiled:
.hero {
background-image: url(data:image/png;base64,bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICJpbWcvc2VsZWN0Mi0yY2E2MWI3NmUyMjA1MzU3MWRkODYxMWU1YWFjNDkwMC5wbmciOw==);
background-repeat: no-repeat;
}
The directory looks like this: