Setting Up vanilla-extract with Vite
You'll learn how to install and configure vanilla-extract to write type-safe, zero-runtime CSS in your React project.
The Setup Process
Vanilla-extract brings zero-runtime CSS-in-JS to your project, but it needs build-time tooling to transform .css.ts files into actual CSS. With Vite, this integration is straightforward.
Think of vanilla-extract as a translator: you write TypeScript files that describe styles, and the Vite plugin converts them into optimized CSS during the build, not when your app runs in the browser. This is the "zero-runtime" magic—no JavaScript executes at runtime to calculate styles.
Installation
You need two packages:
npm install @vanilla-extract/css
npm install --save-dev @vanilla-extract/vite-plugin
The @vanilla-extract/css package provides the functions you'll use to define styles. The Vite plugin handles the build-time transformation.
Vite Configuration
Add the plugin to your vite.config.js:
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';
export default defineConfig({
plugins: [react(), vanillaExtractPlugin()],
});
That's it! Now you can create .css.ts files alongside your components and import the generated class names directly.
What You Enabled
With this setup, Vite will:
- Process
.css.tsfiles during development and build - Generate optimized CSS with scoped class names
- Provide type-safe style objects
- Enable hot module replacement for style changes
Key Takeaway: Setting up vanilla-extract requires installing @vanilla-extract/css and adding the Vite plugin to your config—once configured, you can write type-safe styles in .css.ts files that compile to zero-runtime CSS.