Lesson 10 / 25

CSS and styling

Bundle and optimize CSS with Webpack.

CSS bundling strategies

CSS can be imported and injected into the DOM via style-loader, or extracted to separate files using MiniCssExtractPlugin. Extracted CSS allows caching and parallel downloads. PostCSS processes CSS with plugins for autoprefixing and minification.

Extract CSS to files

Configure MiniCssExtractPlugin for production builds.

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = {
  module: {
    rules: [{
      test: /\.css$/,
      use: [
        process.env.NODE_ENV === 'production' 
          ? MiniCssExtractPlugin.loader 
          : 'style-loader',
        'css-loader'
      ]
    }]
  },
  plugins: [new MiniCssExtractPlugin()]
};

Output:

CSS extracted to separate .css files in production

CSS module scoping

Enable CSS modules to scope class names locally, avoiding conflicts. Use loader option modules: true. This transforms .button { } to unique class names like Button_button__a1b2c in output.

Quick check

Quick check: What is the advantage of extracting CSS?

  • Enables caching and parallel downloads.
  • Reduces CSS file size.
  • Prevents CSS from being used.
Answer

Enables caching and parallel downloads. — Extracted CSS files can be cached separately and downloaded in parallel with JavaScript, improving load performance.