CSS and Style Loaders
What You'll Learn
You'll learn how to use css-loader and style-loader together to import CSS files directly into your JavaScript modules and inject those styles into the browser.
The Problem: JavaScript Can't Handle CSS Natively
Webpack's core job is to bundle JavaScript, but modern web apps need to manage CSS too. When you write import './styles.css' in JavaScript, Webpack doesn't know what to do with that CSS file—it needs loaders to transform it into something JavaScript can understand.
How CSS Loaders Work
Think of loaders as translators in a pipeline:
css-loader reads your CSS file and resolves any @import and url() statements, converting the CSS into a JavaScript string representation.
style-loader takes that JavaScript string and injects it into the DOM by creating a <style> tag in the document's <head>.
Using Them Together
// webpack.config.js
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
};
Notice the order: use processes right-to-left, so css-loader runs first, then style-loader.
Now in your JavaScript:
import './app.css';
Webpack processes app.css through both loaders, and the styles automatically appear in your page when the JavaScript bundle loads.
The Development Advantage
This approach means your CSS is bundled with your JavaScript during development, with hot reloading support. When you change a CSS file, only those styles update—no full page refresh needed.
Key Takeaway: css-loader interprets CSS imports and turns them into JavaScript modules, while style-loader injects those styles into the DOM at runtime—together they let you import CSS just like any other JavaScript module.