Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท Assets and CSS

Importing CSS and CSS Modules

Learn how Vite handles plain CSS imports, CSS Modules with scoped class names, global and local selectors, css.modules options, CSS code splitting, inline styles and lightningcss.

Styles in a Vite project are first-class modules. You import a CSS file from JavaScript and Vite takes care of injecting it, updating it instantly when you edit, extracting it into real .css files in production, and optionally scoping class names to the file that uses them. This lesson covers plain CSS, CSS Modules, and what Vite does with each during development and build.

Vite is not installed on this site, so the Vite code is read-only. Runnable examples show the browser behaviour (injecting a style element) and a stand-in for CSS Modules name hashing.

Importing a stylesheet

JavaScript
// main.js
import './style.css';
import './components/card.css';

An import with no binding means "I want the side effect of this CSS being on the page". Where you import it does not matter for the page as a whole: all imported CSS is global, applying to every element on the page.

You can also link CSS from index.html, and @import other files from CSS:

CSS
/* style.css */
@import './variables.css';
@import './reset.css';

:root { --brand: #0a7; }
body { font-family: system-ui, sans-serif; }

Vite inlines @import chains with PostCSS, so imported files are bundled into the importing stylesheet.

What happens in development

In dev, a CSS import is turned into a JavaScript module that creates (or updates) a <style> element. That is why CSS edits apply instantly and without a reload: HMR just swaps the text of that style tag.

This runnable demo does exactly what that module does.

What a CSS import becomes in dev

What happens in a build

During vite build, CSS is extracted from the JavaScript into .css files with content hashes, and the HTML gets a <link rel="stylesheet"> for it:

TEXT
dist/assets/index-4b1c8a2e.css
dist/assets/index-9f3d7e10.js

Extraction lets the browser download CSS in parallel with JavaScript and cache it independently.

CSS code splitting

If your app uses dynamic imports (import('./Admin.js')), the CSS that only that chunk needs is split into its own file and loaded together with the chunk. This is on by default (build.cssCodeSplit: true). Turn it off to get a single CSS file for the whole app:

JavaScript
build: { cssCodeSplit: false }

CSS Modules

A file named *.module.css is a CSS Module. Its class names are rewritten to unique, file-scoped names, and the import gives you an object mapping the original names to the generated ones.

CSS
/* Card.module.css */
.card { border: 1px solid #ccc; padding: 1rem; }
.title { font-weight: 700; }
.title:hover { color: crimson; }
JavaScript
import styles from './Card.module.css';

const el = document.createElement('article');
el.className = styles.card;
el.innerHTML = `<h2 class="${styles.title}">Hello</h2>`;

console.log(styles.card); // e.g. "_card_x7k2a_1" in dev, "_card_x7k2a" style hash in build

Because names are generated per file, .title in Card.module.css cannot clash with .title in Banner.module.css. You get component-level scoping without a framework.

Named imports

JavaScript
import { card, title } from './Card.module.css';

Named imports work when the class names are valid JavaScript identifiers. Dashed names like .card-title need the default object (styles['card-title']) or css.modules.localsConvention: 'camelCase', which also exposes cardTitle.

:global and composes

CSS
/* Inside a module file */
:global(.dark) .card { background: #111; }   /* .dark stays as-is */
.button { composes: base from './shared.module.css'; }  /* reuse another class */
:global { body { margin: 0; } }              /* a whole block, unscoped */

composes lists several generated class names on the same element, so you can share rules without duplicating them.

A model of name scoping

The generated names come from a hash of the file path and the class name. This stand-in shows the mapping idea. Vite's real hashing differs, but the effect is the same: same file and class give the same name; different files give different names.

Node.js Stand-in: scoping class names per file

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.

Configuring CSS Modules

JavaScript
export default defineConfig({
  css: {
    modules: {
      localsConvention: 'camelCaseOnly',          // card-title -> cardTitle
      generateScopedName: '[name]__[local]___[hash:base64:5]',
      scopeBehaviour: 'local',                    // or 'global'
    },
  },
});

A readable generateScopedName such as [name]__[local] in development makes the DevTools output easier to read. In production, short hashes keep the HTML small.

TypeScript types for CSS Modules

vite/client types declare *.module.css as an object with string values, so styles.anything type checks (and typos are not caught). For exact class names use a plugin such as typed-css-modules or typescript-plugin-css-modules in the editor.

Importing CSS as text and getting the URL

Import Result
import './a.css' Side effect: styles applied
import styles from './a.module.css' Class name map
import css from './a.css?inline' CSS text, not injected (handy for web components and shadow DOM)
import url from './a.css?url' URL of the emitted CSS file

For a web component, ?inline is the right tool:

JavaScript
import cssText from './my-element.css?inline';

const sheet = new CSSStyleSheet();
sheet.replaceSync(cssText);
shadowRoot.adoptedStyleSheets = [sheet];

Source maps, minification and modern CSS

  • css.devSourcemap: true shows original file and line in DevTools during development.
  • Production CSS is minified by esbuild by default; build.cssMinify can switch to 'lightningcss'.
  • Lightning CSS is a fast Rust CSS transformer. Enable it with css.transformer: 'lightningcss'; it handles vendor prefixes, modern syntax lowering (nesting, color-mix()) for your build.target browsers, and CSS Modules.
  • build.cssTarget sets the browsers CSS should support when different from the JavaScript target.

A second runnable check: composing classes

Node.js Class lists from composes

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.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Vite turn import './style.css' into during development?

    In dev, CSS becomes a JS module that manages a style tag, which makes CSS HMR instant.
  2. 2. Which file name makes Vite treat a stylesheet as a CSS Module?

    Files ending in .module.css (and .module.scss and so on) get scoped class names.
  3. 3. You want a class in a CSS Module to keep its original name. What do you use?

    :global(...) leaves the wrapped selector unscoped.
  4. 4. How do you get a stylesheet's text without injecting it into the page?

    The ?inline suffix returns the processed CSS as a string, useful for shadow DOM.

Summary

  • Import CSS from JavaScript; in dev it becomes an injected style tag with instant HMR, in builds it is extracted into hashed .css files.
  • cssCodeSplit keeps CSS for dynamic chunks in separate files.
  • *.module.css files give scoped class names through an imported object; use :global and composes as needed.
  • ?inline returns CSS as text, ?url gives the emitted file URL.
  • Lightning CSS can replace PostCSS for transforms and minification.

Next: Sass, Less and PostCSS