Vite Plugin
Enhance your Vite development experience with HMR and style validation
The optional @typestyles/vite plugin enhances your development experience with Hot Module Replacement (HMR) and helpful warnings.
Runnable examples: examples/vite-app (React), examples/vue-app, examples/svelte-app, and examples/typewind. Each includes a convention entry and production extraction.
Installation
npm install -D @typestyles/vite
# or
pnpm add -D @typestyles/vite
# or
yarn add -D @typestyles/vite
Basic setup
Add the plugin to your vite.config.ts:
import { defineConfig } from 'vite';
import typestyles from '@typestyles/vite';
export default defineConfig({
plugins: [typestyles()],
});
For zero-runtime production builds while keeping runtime + HMR in development, add a convention style entry (e.g. src/typestyles-entry.ts) or set extract.modules (see Zero-runtime extraction). When at least one extraction module resolves, the plugin defaults to mode: 'build': vite dev still injects styles at runtime, and vite build emits a static CSS file and strips client injection.
For loading self-hosted fonts with Vite’s asset pipeline, see Fonts.
Features
Hot Module Replacement (HMR)
Without the plugin, editing a style file causes a full page reload. With the plugin:
- Style changes apply instantly
- Component state is preserved
- No flicker or re-render cascade
The plugin works by:
- Detecting when a module uses typestyles
- Injecting HMR accept handlers
- Invalidating affected style registrations on file change
- Triggering a targeted update instead of a full reload
Duplicate namespace warnings
The plugin warns you when multiple files use the same namespace:
Style namespace "button" is also used in /path/to/other/file.ts.
Duplicate namespaces cause class name collisions.
This helps catch issues early, since duplicate namespaces can cause unexpected style overwrites.
Configuration
Runtime in dev, static CSS in production (recommended for SPAs)
This is the usual setup for Vite: development uses the typestyles runtime so edits hot-reload without running a separate extraction step; production emits a real .css asset the browser can cache and parse in parallel with JS.
Add a convention entry file that imports every registration side effect (see Zero-runtime extraction), or set extract.modules explicitly. You do not need to pass mode — when modules resolve (discovered or explicit), it defaults to build, and the plugin only disables the runtime during vite build, not during vite dev.
Using discovery (minimal vite.config):
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import typestyles from '@typestyles/vite';
export default defineConfig({
plugins: [
react(),
typestyles(), // discovers e.g. src/typestyles-entry.ts when present
],
});
Explicit extract (multiple entries or custom paths):
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import typestyles from '@typestyles/vite';
export default defineConfig({
plugins: [
react(),
typestyles({
extract: {
modules: ['src/typestyles-entry.ts'],
fileName: 'assets/typestyles-[hash].css',
},
}),
],
});
Link the generated file from index.html only if you need a custom placement — otherwise the plugin injects <link rel="stylesheet" href="…"> into every HTML entry. In dev the middleware serves a stable URL (/typestyles.css, or your fileName with hash placeholders removed). Production builds emit a content-hashed asset (Vite assetFileNames, usually assets/typestyles-<hash>.css) and rewrite that link to the hashed href, including a hardcoded /typestyles.css. Set extract.fileName to a literal such as typestyles.css to keep a fixed production path. [name], [hash], [hash:N], [ext], and [extname] in fileName are expanded at build time.
To force runtime-only everywhere (no extraction), set mode: 'runtime' even when extract is present. For dynamic values that cannot be extracted, see mode: 'hybrid' in Zero-runtime extraction.
Missing recipes
vite build fails when a local module reachable from the app calls recipe() and that module is missing from the extract entry. The message names the file and the recipe name (libraryPlayer in src/player.ts). Add the import to the convention entry.
Set coverage: false when the production extract is meant to cover only part of the app. style(), tokens, and themes are unchanged: they are included only when the extract entry runs them.
Disable duplicate warnings
If you have a legitimate use case for duplicate namespaces (uncommon), you can disable the warning:
import { defineConfig } from 'vite';
import typestyles from '@typestyles/vite';
export default defineConfig({
plugins: [
typestyles({
warnDuplicates: false,
}),
],
});
Source comments
Rules in the extracted CSS can carry a comment naming the call that registered them, so you can go from a rule in DevTools to the recipe() or style() call site. It is off by default:
typestyles({ extract: { sourceComments: true } });
/* src/Button.ts:12 */
.button-base {
padding: 8px;
}
Paths are relative to the project root; rules from a library bundled into the extract show the library's path. This applies to the extracted stylesheet only (dev /typestyles.css and vite build). Runtime injection goes through CSSStyleSheet.insertRule, which drops comments. Enable it for debugging rather than production, since it adds bytes and a stack capture per rule at extract time.
Source maps
For a real CSS source map that maps each extracted rule back to the recipe() / style() call that registered it, enable extract.sourceMap:
typestyles({ extract: { sourceMap: true } });
In vite build, the plugin emits a companion .css.map asset and appends a /*# sourceMappingURL=... */ comment to the CSS. In vite dev, the dev-server middleware serves the map at /typestyles.css.map (or your fileName with .map appended) so DevTools can resolve the same mappings for the extracted stylesheet.
Like source comments, this costs one stack capture per rule at extract time and is intended for development/debugging rather than production.
Dev inspect
When styles are injected at runtime (the default in vite dev), CSSStyleSheet.insertRule strips comments, so the source-comment trick above does not help. Instead, TypeStyles can keep a dev-only registry that maps generated class names back to the recipe() / style() call that registered them.
The registry is on by default in non-production builds. Import the helpers in your app entry or open the console:
import { inspect } from 'typestyles/inspect';
inspect('button-base');
// { className: 'button-base', source: 'src/Button.ts:12', css: ['.button-base { ... }'] }
Or use the global that is registered automatically:
window.__TYPESTYLES_INSPECT__.inspect('button-base');
window.__TYPESTYLES_INSPECT__.inspectElement($0);
data-ts-source attribute
In attribute mode, you can also surface the source location directly on elements. Opt in by setting the dev-inspect flag before your recipes execute:
if (typeof window !== 'undefined') {
window.__TYPESTYLES_DEV_INSPECT__ = true;
}
Attribute-mode recipes then emit a data-ts-source attribute:
<button class="button" data-intent="primary" data-ts-source="src/Button.ts:12"></button>
Set the flag to false to disable both the registry and the attribute, or pass { root: '/project/root' } to relativize captured paths.
How HMR works
When you save a file that imports from typestyles, the plugin:
Extracts namespaces: Parses your code to find all
recipe(),tokens.create(),createTheme()/tokens.createTheme({ name }), andkeyframes.create()calls (see End-to-end theming for the theme + override pattern)Injects HMR code: Adds Vite's
import.meta.hothandlers to the moduleOn file change:
- The HMR handler calls
invalidateKeys()fromtypestyles/hmr - Affected styles are removed from the internal registry
- The module re-executes with fresh style definitions
- New CSS is injected, replacing the old rules
- The HMR handler calls
State preserved: React/Vue/Svelte components keep their state since only the module containing styles changed
Example: seeing HMR in action
Create a simple Vite app with typestyles:
// src/tokens.ts
import { createTypeStyles } from 'typestyles';
const { tokens } = createTypeStyles({ scopeId: 'app' });
export const color = tokens.create('color', {
primary: '#0066ff',
});
// src/styles.ts
import { createTypeStyles } from 'typestyles';
const { style, recipe } = createTypeStyles({ scopeId: 'app' });
import { color } from './tokens';
export const button = recipe({
name: 'button',
styles: {
base: {
backgroundColor: color.primary,
padding: '8px 16px',
},
},
});
// src/main.ts
import { button } from './styles';
document.getElementById('app').innerHTML = `
<button class="${button()}">Click me</button>
`;
Run the dev server:
npm run dev
Now edit src/tokens.ts and change the primary color. The button updates instantly without a page reload!
Framework integration
The plugin works with any Vite-based framework:
React
npm create vite@latest my-app -- --template react-ts
npm install typestyles @typestyles/vite
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import typestyles from '@typestyles/vite';
export default defineConfig({
plugins: [react(), typestyles()],
});
Vue
npm create vite@latest my-app -- --template vue-ts
npm install typestyles @typestyles/vite
// vite.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import typestyles from '@typestyles/vite';
export default defineConfig({
plugins: [vue(), typestyles()],
});
Svelte
npm create vite@latest my-app -- --template svelte-ts
npm install typestyles @typestyles/vite
// vite.config.ts
import { defineConfig } from 'vite';
import { svelte } from '@sveltejs/vite-plugin-svelte';
import typestyles from '@typestyles/vite';
export default defineConfig({
plugins: [svelte(), typestyles()],
});
SSR with Vite
HMR hooks are dev-only (import.meta.hot). For build-time extraction, production client bundles get __TYPESTYLES_RUNTIME_DISABLED__ so the sheet does not inject <style> tags; the plugin also redirects typestyles' stylesheet module to a no-op build in client bundles, so the CSS insertion runtime, stylesheet state, and DOM plumbing are absent from the bundle entirely (see Zero-runtime extraction — the no-op sheet). Pair the emitted CSS file or SSR helpers with imports of typestyles/server (unaffected by the redirect) as described in the SSR guide.
Troubleshooting
HMR not working
- Check that the plugin is listed in
vite.config.ts - Ensure your files import from
'typestyles'(not a relative path to the package) - Verify
import.meta.hotis available (dev mode, not production)
Duplicate namespace warnings appearing incorrectly
The detection is regex-based and may have false positives if you:
- Have strings that look like typestyles calls in comments
- Use variable names like
stylesfor other purposes
These are rare and don't affect functionality—just ignore the warning or disable it.
Full reloads still happening
Some changes require a full reload:
- Adding/removing imports that affect the module graph
- Changes to non-typestyles code in the same file
- Type-only changes (TypeScript types don't affect runtime)
Plugin performance
The plugin adds minimal overhead:
- Only transforms files that import from
'typestyles' - Transformation is a simple regex match, not a full AST parse
- HMR helpers are stripped from production bundles; extraction runs only during
vite buildwhen usingbuildorhybridmode
Is the plugin required?
No. TypeStyles works perfectly without it. The plugin improves DX for:
- Faster iteration with HMR
- Early warning about duplicate namespaces
- Optional production CSS extraction via
extract(see Zero-runtime extraction), including the no-op sheet redirect that removes the CSS runtime from production client bundles
If you prefer full page reloads or use a different bundler, you don't need this plugin.
Future features
Planned enhancements (not yet implemented):
- Dead style detection: Warn when styles are defined but never used
Stay tuned to the GitHub repository for updates.