# CSS and styling — Webpack

Source: https://www.geekswithgeeks.com/en/webpack/webpack-10

> 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.

```javascript
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

**Quiz:** What is the advantage of extracting CSS?

- [x] 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.
