Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Entry, Output and Loaders

CSS and Style Loaders

Import CSS in Webpack with css-loader and style-loader, add Sass and PostCSS, use CSS Modules for scoped class names and understand importLoaders, url() handling and the production alternative.

In a Webpack project you import CSS from JavaScript: import './styles.css'. It feels odd the first time, but it gives you a graph that knows which styles each component needs, so unused components bring no CSS along. Two loaders make it work, and a third and fourth add Sass and PostCSS.

Terminal
npm install --save-dev css-loader style-loader

css-loader and style-loader

  • css-loader reads a CSS file, follows @import and url(...), and returns it as a JavaScript module (a string of CSS plus a list of class names).
  • style-loader takes that module and, at runtime, creates a <style> tag in the page with the CSS.
JavaScript
module.exports = {
  module: {
    rules: [
      { test: /\.css$/i, use: ['style-loader', 'css-loader'] },
    ],
  },
};

Order matters: right to left means css-loader runs first (Loaders Basics). Swap them and the build fails with a confusing syntax error, because style-loader would receive raw CSS.

JavaScript
// src/index.js
import './styles.css';
import { render } from './app.js';

render();

style-loader injects styles when the bundle runs, which is perfect for development because it supports hot updates (Hot Module Replacement). For production you normally replace it with a plugin that writes real .css files (MiniCssExtractPlugin), so the browser can download CSS in parallel with JavaScript and avoid a flash of unstyled content.

What css-loader does to url() and @import

Inside CSS, url('./hero.png') and @import './base.css' are treated like JavaScript imports: Webpack resolves them, adds the image to the graph, and rewrites the path to the hashed output name.

CSS
/* src/hero.css */
@import './base.css';

.hero {
  background: url('./hero.jpg') center / cover;
}

If hero.jpg has a matching rule (for example type: 'asset/resource', see Asset Modules), the final CSS points at hero.3c1f9e.jpg. Absolute URLs (/images/x.png or https://...) are left alone.

Sass and PostCSS

Add more loaders to the right of css-loader, so they run first:

Terminal
npm install --save-dev sass sass-loader postcss postcss-loader postcss-preset-env
JavaScript
{
  test: /\.s[ac]ss$/i,
  use: [
    'style-loader',
    { loader: 'css-loader', options: { importLoaders: 2 } },
    'postcss-loader',
    'sass-loader',
  ],
}

The flow is Sass to plain CSS, then PostCSS adds vendor prefixes and modern syntax support, then css-loader, then style-loader. A postcss.config.js holds the PostCSS plugins:

JavaScript
module.exports = {
  plugins: ['postcss-preset-env'],
};

importLoaders is the option people forget. When one CSS file @imports another, css-loader must tell Webpack how many of the loaders after it (to the right) should also process the imported file. With Sass and PostCSS that is 2.

CSS Modules: local class names

A global stylesheet can collide: two components may both use .title. CSS Modules make class names local by generating unique names at build time.

JavaScript
{
  test: /\.module\.css$/i,
  use: [
    'style-loader',
    { loader: 'css-loader', options: { modules: { localIdentName: '[name]__[local]--[hash:base64:5]' } } },
  ],
}
CSS
/* button.module.css */
.primary { background: royalblue; color: white; }
JavaScript
import styles from './button.module.css';

button.className = styles.primary; // "button__primary--x7Qp2"

The imported object maps your readable name to the generated one, so another file's .primary cannot clash.

Node.js Stand-in: scope class names like CSS Modules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Global styles next to modules

A common setup uses module scoping only for files named *.module.css, and treats everything else as global. In css-loader 7 this is the default with modules: { auto: true }: files ending with .module.css are modules. Use :global(.selector) inside a module to opt a class out of renaming.

Injecting styles: a closer look

What style-loader does at runtime is small enough to imitate. This stand-in has no DOM, so it records the style tags it would create.

Node.js Stand-in: what style-loader injects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Troubleshooting

  • "You may need an appropriate loader to handle this file type." The rule's test does not match, or the loader is not installed.
  • Styles apply in dev but flash on load in production. You shipped style-loader; switch to the extract plugin.
  • @imported Sass files miss PostCSS. Set importLoaders.
  • A class name is undefined. The file is not treated as a module (name or modules option) or you imported the wrong export.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the job of css-loader?

    css-loader interprets the CSS and exposes it to the module graph; style-loader does the injection.
  2. 2. Why is 'style-loader' listed first in the use array?

    The first entry is the last to run, which is what style-loader needs after css-loader.
  3. 3. What does importLoaders: 2 mean for css-loader?

    It controls how many following loaders process files that are brought in by @import.
  4. 4. What problem do CSS Modules solve?

    Each class name is scoped to its file through a generated unique name.

Summary

  • css-loader turns CSS into a module and resolves @import and url(); style-loader injects it with a <style> tag.
  • Add sass-loader and postcss-loader to its right, and set importLoaders accordingly.
  • CSS Modules scope class names; the import gives a map from your name to the generated one.
  • Use style-loader in development and an extract plugin in production.

Next: Babel and TypeScript Loaders