Vite

Scoping component CSS with Vite and PostCSS

See how Vite rewrites CSS Module class names, configure readable development names and PostCSS transforms, and check the compiled CSS.

Scoping component CSS with Vite and PostCSS

Two components can each use a class named container without sharing the same CSS rule. Vite turns local selectors into generated names at build time and lets PostCSS adapt the resulting stylesheet for the browser targets.

The example uses Vite’s PostCSS-based CSS pipeline, React, TypeScript, Autoprefixer, and PostCSS Preset Env.

Scope styles without relying on naming conventions

Naming conventions such as BEM can keep global selectors organized. They rely on each contributor following the pattern. Runtime CSS-in-JS libraries can provide scoped styles and dynamic values, but they may also add JavaScript work to parse or inject styles and require care around server rendering and hydration.

CSS Modules makes the component’s selector mapping a build-time concern. I write ordinary CSS in a .module.css file and import a map of generated class names. The browser reads CSS and applies the classes on the element. It does not need to generate style rules from a component’s JavaScript at render time.

Follow the compiled style into the component

Vite’s CSS plugins recognize module filenames, including preprocessed variants such as .module.scss and .module.less when their preprocessors are configured. In a PostCSS-based build, the module transformation replaces local selectors and emits JavaScript exports containing the generated names. The production CSS can be extracted into a separate chunk.

flowchart TD
    A["Button.module.css<br/>(.container { ... })"] --> B["Vite CSS pipeline (PostCSS)"]
    
    subgraph TransformPhase["1. CSS Modules scoping"]
        B --> C["Generate a scoped class name<br/>Button_container__a8B3c"]
        C --> D["Create the class map<br/>{ container: 'Button_container__a8B3c' }"]
    end
    subgraph OutputPhase["2. Emit CSS and JavaScript"]
        D --> E["Export a JavaScript map<br/>export default { container: '...' }"]
        C --> F["Bundle a CSS chunk<br/>dist/assets/index-[hash].css"]
    end
    E --> G["Use the map in a component: &lt;button className={styles.container}&gt;"]

If two files each declare .container, the naming function can produce a distinct name for each declaration. The imported object gives a component the right value to assign, including after the file is moved or the generated name changes.

Set naming and browser targets in the Vite config

I choose a readable development pattern when inspecting elements and a compact pattern for production output. This configuration also converts local class names to camel-case properties and runs Autoprefixer and PostCSS Preset Env.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// vite.config.ts
import { defineConfig } from 'vite';
import autoprefixer from 'autoprefixer';
import postcssPresetEnv from 'postcss-preset-env';

export default defineConfig(({ mode }) => {
  const isDev = mode === 'development';

  return {
    css: {
      modules: {
        // Template for the scoped class name
        // Development: file name, local class, and a short hash
        // Production: underscore plus an eight-character hash
        generateScopedName: isDev
          ? '[name]_[local]__[hash:base64:5]'
          : '_[hash:base64:8]',

        // Expose kebab-case classes as camelCase properties
        // .button-container -> styles.buttonContainer
        localsConvention: 'camelCaseOnly',

        // Scope mode (default: local)
        scopeBehaviour: 'local'
      },
      postcss: {
        plugins: [
          // 1. Add vendor prefixes for the supported browsers
          autoprefixer(),
          // 2. Transform selected newer CSS syntax for older browsers
          postcssPresetEnv({
            stage: 2,
            features: {
              'nesting-rules': true
            }
          })
        ]
      }
    }
  };
});

The browser list tells compatible PostCSS plugins what their output must support. Keep it alongside the Vite configuration so changes to supported browsers are reviewable.

1
2
3
4
5
# .browserslistrc
> 0.5%
last 2 versions
Firefox ESR
not dead

Autoprefixer inserts vendor prefixes according to the target set. Preset Env can lower selected newer CSS features, including nesting. Check how prefixing is configured across the two plugins if the project changes its preset options. When using a different CSS transformer in Vite, confirm it accepts the same module and PostCSS settings before reusing this configuration.

Write local rules and keep global selectors explicit

A module can opt a selector out of name scoping with :global. I use that when a local component needs to style a class controlled by another library or a global icon convention. The boundary should remain visible in the stylesheet because the global part can affect matching elements outside the component.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* src/components/Button.module.css */
.container {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0.625rem 1.25rem;
  border-radius: 0.5rem;
  font-weight: 600;
  cursor: pointer;
  user-select: none;
  transition: all 0.2s ease-in-out;
}

.primary {
  background-color: #89b4fa;
  color: #1e1e2e;
}

/* Match a global icon or a third-party selector */
.container :global(.custom-icon) {
  margin-right: 0.5rem;
  fill: currentColor;
}

With localsConvention: 'camelCaseOnly', a selector written in kebab case can be accessed through a camel-case property on the imported styles object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// src/components/Button.tsx
import React from 'react';
import styles from './Button.module.css';

interface ButtonProps {
  variant?: 'primary' | 'secondary';
  children: React.ReactNode;
  onClick?: () => void;
}

export function Button({ variant = 'primary', children, onClick }: ButtonProps) {
  return (
    <button
      type="button"
      className={`${styles.container} ${styles[variant]}`}
      onClick={onClick}
    >
      {children}
    </button>
  );
}

Vite’s client declarations cover typical CSS imports. The following ambient module shape also lets TypeScript understand an imported map of strings. It cannot verify the spelling of an individual class since the index signature accepts any string. For stricter checks, generate per-file declarations or use tooling such as vite-plugin-sass-dts or typescript-plugin-css-modules where it fits the project.

1
2
3
4
5
6
7
// src/vite-env.d.ts
/// <reference types="vite/client" />

declare module '*.module.css' {
  const classes: { readonly [key: string]: string };
  export default classes;
}

Verify the generated class names and transforms

Run pnpm vite build and inspect the emitted CSS and an HTML element rendered by the component. The sample output includes class names such as Button_container__a8B3c. The exact name follows the selected mode and template, so I verify that the CSS selector and the runtime class match.

Vite terminal output showing generated CSS Modules selectors and chunks Figure 1. The build shows scoped names and an emitted CSS chunk.

I also inspect a rule that exercises the browser target configuration. The sample shows prefixes on properties such as user-select and backdrop-filter. Which forms appear depends on the target list and plugin versions.

Terminal output showing PostCSS vendor prefix and modern CSS transforms Figure 2. The generated stylesheet shows target-dependent vendor prefixes.

Before changing the stylesheet stack, I check scope isolation across two components with the same local class, verify global exceptions, and test the resulting CSS in the supported browsers. That covers the generated names and the behavior they are meant to support.

Vite CSS Modules options

This post is licensed under CC BY 4.0 by the author.