TExcelTAD
Home › Vite › Vite CSS & CSS Modules

Vite CSS & CSS Modules

Vite treats CSS as a first-class module. You can import stylesheets from JavaScript, use @import with path resolution, scope class names with CSS Modules, and get hot updates without reloading.

Importing a stylesheet

js
// src/main.js
import './style.css';
Mode What happens
Dev The CSS is injected into a <style> tag; saving the file hot-swaps it
Build All imported CSS is extracted into dist/assets/index-[hash].css and linked from index.html

You can also link CSS directly from HTML with <link rel="stylesheet" href="/src/style.css"> — Vite processes and bundles it the same way.

@import and url() are resolved for you, including aliases and packages:

css
/* src/style.css */
@import 'modern-normalize/modern-normalize.css'; /* from node_modules */
@import './theme.css';

body {
  background: url('./img/noise.png');
}

CSS Modules

Any file ending in .module.css is a CSS Module. Its class names are made unique per file, and importing it returns an object that maps your names to the generated ones.

css
/* src/Button.module.css */
.button {
  padding: 0.5rem 1rem;
  border-radius: 6px;
}
.primary {
  background: #646cff;
  color: white;
}
js
// src/Button.js
import styles from './Button.module.css';

export function Button(label) {
  const el = document.createElement('button');
  el.className = `${styles.button} ${styles.primary}`;
  el.textContent = label;
  return el;
}

styles.button is something like _button_t92z_1. Another file can also define .button without any clash.

How scoping works

The playground imitates what a CSS Modules transform does: rename every class with a file-based hash and return the mapping.

js · try it yourself
function cssModule(fileName, css) {
  const hash = [...fileName].reduce((h, ch) => (h * 31 + ch.charCodeAt(0)) % 100000, 7).toString(36);
  const map = {};
  const scoped = css.replace(/\.([a-zA-Z_][\w-]*)/g, (_, name) => {
    map[name] = `_${name}_${hash}`;
    return '.' + map[name];
  });
  return { map, scoped };
}

const a = cssModule('Button.module.css', '.button { color: white } .primary { background: blue }');
const b = cssModule('Card.module.css', '.button { color: black }');

console.log(a.map);
console.log(b.map);
console.log(a.scoped);
{"button":"_button_t92","primary":"_primary_t92"}
{"button":"_button_1p3s"}
._button_t92 { color: white } ._primary_t92 { background: blue }

Two files, two different .button classes — no collisions.

Configuring CSS Modules

js
// vite.config.js
export default {
  css: {
    modules: {
      localsConvention: 'camelCaseOnly', // .nav-item → styles.navItem
      generateScopedName: '[name]__[local]__[hash:base64:5]',
    },
  },
};
Option Effect
localsConvention 'camelCase', 'camelCaseOnly', 'dashes', 'dashesOnly' — how keys are exposed
generateScopedName Pattern or function for generated names (readable names help debugging)
scopeBehaviour 'local' (default) or 'global'

Inside a module you can still opt out with :global(.some-class) when you need to style third-party markup.

Live: scoped vs. global

This page renders two "components" that both use a class called title. The left one uses global CSS (and gets overridden), the right one uses a scoped name like CSS Modules would produce.

html · try it yourself
<!doctype html>
<html>
  <head>
    <style>
      body { font-family: system-ui; display: flex; gap: 1rem; padding: 1rem; }
      .card { border: 1px solid #ccc; border-radius: 8px; padding: 1rem; width: 180px; }
      /* component A (global) */
      .title { color: #646cff; }
      /* component B, loaded later, also writes .title globally… */
      .title { color: crimson; text-decoration: underline; }
      /* component C uses a CSS Module: unique class */
      ._title_k3j9a { color: #2e7d32; }
    </style>
  </head>
  <body>
    <div class="card"><h3 class="title">Global .title</h3><p>Clobbered by another file.</p></div>
    <div class="card"><h3 class="_title_k3j9a">Module .title</h3><p>Scoped, safe.</p></div>
  </body>
</html>

Other CSS features

Feature How
Import CSS as a string import css from './x.css?inline' (not injected)
Disable injection, get URL import url from './x.css?url'
Source maps in dev css: { devSourcemap: true }
Code-split CSS CSS imported by a lazy chunk becomes its own file, loaded with the chunk
Minification Lightning CSS in Vite 8 (build.cssMinify)
Browser targets build.cssTarget for syntax lowering

?inline is useful for Shadow DOM components that need the CSS text:

js
import styles from './widget.css?inline';

class MyWidget extends HTMLElement {
  connectedCallback() {
    const root = this.attachShadow({ mode: 'open' });
    root.innerHTML = `<style>${styles}</style><slot></slot>`;
  }
}
customElements.define('my-widget', MyWidget);

Tip: Global styles (resets, typography, CSS variables) belong in a normal .css file imported once from main.js. Component styles are where CSS Modules shine.

Test yourself

Which file name makes Vite treat a stylesheet as a CSS Module?

  1. styles.css
  2. styles.scoped.css
  3. styles.module.css
  4. styles.local.css

What does import styles from './Card.module.css' return?

  1. The CSS text
  2. A URL to the CSS file
  3. An object mapping class names to generated unique names
  4. Nothing; it is side-effect only

In a production build, where does CSS imported from JavaScript end up?

  1. Inline in every JS file
  2. In a separate hashed .css file linked from index.html
  3. In public/
  4. It is discarded