style-loader
takes CSS you've imported in your JavaScript files, and injects them as <style></style>
tags into the DOM. It's particularly useful for inlining Critical CSS into the <head>
of your page.
If you decide to self-host your fonts instead of using Google Fonts, style-loader
can also help you inline your font declarations so the browser knows immediately what to do with the font files it downloads.
/* style.css */
body {
background: green;
}
/* component.js */
import './style.css';
/* webpack.config.js */
module.exports = {
module: {
rules: [
{
test: /\.css$/i,
use: ['style-loader', 'css-loader'],
},
],
},
};
mini-css-extract-plugin
on the other hand, extracts your CSS into separate files.
It generates a CSS file for each JS file that imports CSS. It's more useful for CSS that you want to load asynchronously.
/* webpack.config.js */
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
plugins: [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// all options are optional
filename: '[name].css',
chunkFilename: '[id].css',
ignoreOrder: false, // Enable to remove warnings about conflicting order
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publicPath here
// by default it uses publicPath in webpackOptions.output
publicPath: '../',
hmr: process.env.NODE_ENV === 'development',
},
},
'css-loader',
],
},
],
},
};
Enjoyed this post? Receive the next one in your inbox!