styledStatic()
Vite plugin that transforms styled-static syntax into optimized React components with static CSS extraction. The plugin runs withenforce: 'post' to execute after the React plugin, ensuring JSX is already transformed. This allows it to work with all file types: .js, .jsx, .ts, .tsx, .mjs, .cjs, etc.
Basic Usage
With Configuration
Configuration Options
Prefix for generated class names. In development mode, class names include the component name and file for easier debugging. In production, they use content hashes for minimal size.
Enable debug logging to see transformation details, file processing, and CSS output decisions. Can also be enabled via
DEBUG_STYLED_STATIC=true environment variable.Debug logs expose file paths and internal state; disable in production for security.Controls how CSS is output during the build process.
Modes
auto (default)- Library builds (
build.libset): Usesfilemode - App builds: Uses
virtualmode - Automatically chooses the best mode for your build type
virtual- CSS is generated as virtual modules
- Vite bundles all CSS into a single file
- Best for applications where you want a single CSS bundle
- No tree-shaking of unused styles
file- CSS is emitted as separate files co-located with JS chunks
- Enables tree-shaking for library builds
- Each JS chunk gets a corresponding CSS file
- Consumers only import CSS for components they use
Examples
Zero Dependencies
The plugin has no direct dependencies and uses:- Vite’s built-in parser (via Rollup’s acorn)
- Native CSS nesting (Chrome 112+, Safari 16.5+, Firefox 117+, Edge 112+)
- Vite’s CSS pipeline for processing
Optional: Lightning CSS
For faster CSS processing and better browser compatibility, installlightningcss:
vite.config.ts:
Transformation Pipeline
The plugin processes files in the following steps:- Parse - Uses Vite’s built-in parser (post-React transform)
- Extract - Finds all
styled/css/createGlobalStyletagged templates - Transform - For each template:
- Extracts CSS content
- Generates unique class name via hash
- Creates virtual CSS module
- Replaces original code with runtime call + import
- Output - Returns transformed code with source map
CSS Cascade Order
When components are extended, classes are ordered for proper CSS cascade:- Base styles are applied first
- Extension styles override base styles
- User
classNameprop overrides all styles
Hot Module Replacement
The plugin includes full HMR support:- CSS changes update instantly without page reload
- Virtual modules are invalidated on file changes
- Style tags are replaced in-place during development
Type Safety
The plugin is fully typed and exports theStyledStaticOptions interface: