@gustcss/vite
v0.13.0
Published
Vite plugin for GustCSS
Maintainers
Readme
@gustcss/vite
Vite plugin for GustCSS - Lightning-fast CSS utility generator.
Installation
npm install gustcss @gustcss/viteUsage
Basic Setup
In your vite.config.js or vite.config.ts:
import { defineConfig } from 'vite'
import gustcss from '@gustcss/vite'
export default defineConfig({
plugins: [
gustcss({
output: 'src/styles/utility.css',
}),
],
})Import Generated CSS
In your main entry file (e.g., src/main.js):
import './styles/utility.css'Configuration
Using Plugin Options
export default defineConfig({
plugins: [
gustcss({
content: ['./src/**/*.{js,ts,jsx,tsx,vue,astro}'],
output: 'src/styles/utility.css',
config: './gustcss.config.json', // Optional: path to config file
}),
],
})Using Config File
Create gustcss.config.json in your project root:
{
"content": ["./src/**/*.{js,ts,jsx,tsx,vue,astro}"],
"output": "src/styles/utility.css",
"darkMode": "class",
"theme": {
"extend": {
"colors": {
"brand": "#3B82F6"
}
}
}
}Dev-Server Linting
Set lint to report class names that generate no CSS while the dev server runs.
The plugin runs gustcss lint --json on startup and after source changes, and
prints the diagnostics through the Vite logger.
The lint process runs asynchronously: at most one runs at a time, changes that
arrive while it runs are coalesced into a single follow-up run, and unchanged
results are not printed twice. Lint problems never stop the dev server, and the
child process is killed when the server closes.
export default defineConfig({
plugins: [gustcss({ lint: true })],
})Pass { strict: true } to also report custom-looking classes and low-confidence
extractions (gustcss lint --strict).
The same check runs on demand with the CLI (gustcss lint), which is what CI
should use. See the CLI documentation for rules, configuration, and baselines.
Production Class-Name Mangling
Enable mangleClassNames to shorten generated selectors and matching source references during vite build.
Development mode keeps readable class names.
The mangler also rewrites class literals passed to the class-composition helpers cn, cx, clsx, classNames, cva, tv, twMerge, and twJoin (the same default list the CLI scanner extracts class names from).
Variant helpers (cva, tv) keep their object keys untouched, because those keys are variant names, not classes. For clsx-style helpers the quoted object keys are classes and are rewritten.
A class reference the mangler cannot rewrite stops the build: an aliased helper (import { cn as merge }), an unquoted clsx object key, or a mapped class inside an unknown string. Add the class to mangleExclude or move the reference to a static string when the build reports one of those errors.
export default defineConfig({
plugins: [
gustcss({
output: 'src/styles/utility.css',
mangleClassNames: true,
mangleExclude: ['public-hook'],
}),
],
})The manifest defaults to <output>.classes.json; set mangleMap to use another path. A path inside Vite's outDir is fine: the plugin writes the manifest again after emptyOutDir runs.
Treat the manifest as generated output and ignore it in Git unless your workflow intentionally pins class mappings.
The transformer supports HTML, JavaScript, TypeScript, JSX, TSX, and Astro. It rewrites static class and className attributes, static template segments, direct string arguments to classList, and setAttribute('class', ...). Code examples inside HTML <code> and <pre> bodies are neither rewritten nor inspected; classes on the elements themselves are still rewritten. An unclosed <code> or <pre> fails the build instead of masking the remainder of the document.
Astro templates (.astro) are rewritten before the Astro compiler sees them. Astro's own Vite plugins run ahead of user plugins, so the rewrite happens in the plugin's load hook on the raw source, guided by the AST that parse() from @astrojs/compiler returns (the package ships with astro, so nothing extra has to be installed). Attribute kinds, the frontmatter, comments, <style> and <script> blocks are taken from that AST.
Rewritten:
- Static
class="…"attributes andclass={"…"}expressions that consist of a single string literal class:listarray elements (including the right operand ofcond && "flex") and quoted object keys, nested arrays and objects includedclassList.add("…")/setAttribute("class", "…")calls in the frontmatter and in<script>blocks
Fail-closed (the build stops when a mapped class appears in one of these places):
- Any
classexpression other than a single string literal, such asclass={cond ? "flex" : "x"}orclass={`flex ${x}`} - Inside
class:list: unquoted keys ({ flex: on }), shorthand properties ({ hidden }), template literals, comparison operands (variant === "flex"), subscripts (map["flex"]), function calls, method chains, or an expression that is not an array/object literal - Component props other than
class/class:list(<Card klass="flex" />),set:html/set:textvalues, strings inside{}expressions ({JSON.stringify("flex")}), and ambiguous strings in the frontmatter or<script>. Aclassorclass:listpassed to a component is rewritten as a static value, like JSXclassName; forwardAstro.props.classunchanged on the receiving side <style>selectors (.flex,@scope (.flex),[class~="flex"]); add hand-written selectors such as.sr-only { … }tomangleExclude
HTML comments, <code> / <pre> bodies, ordinary non-class attributes (<input type="flex">) and <style> declarations (border: 1px solid) are neither rewritten nor inspected.
JavaScript, TypeScript, JSX, TSX, and Astro frontmatter transforms emit Source Map v3 mappings back to the original source. Comments and ordinary strings containing class="..." are not treated as JSX attributes. An ordinary string that still references a mapped class fails closed as ambiguous.
Conditional expressions, nested calls, selectors, and other ambiguous references fail the build. The plugin restores readable CSS after a failed transform.
Add dynamically or externally referenced class names, including production E2E selectors, to mangleExclude.
Vue and Svelte templates are not supported by this option. A mapped class in one of these files fails the build instead of emitting mismatched output.
Files under node_modules are neither rewritten nor inspected.
Short names avoid every class token found in the scanned content files, safelist, and mangleExclude. One- or two-letter classes defined outside content can still collide; add them to mangleExclude.
el.className = '...' assignments are not rewritten and fail the build when they contain a mapped class. Use setAttribute('class', ...) or classList instead.
This optimization is not available through the PostCSS plugin because PostCSS cannot rewrite application markup and JavaScript.
Features
⚡️ Development Mode
- Watches your source files for changes
- Regenerates CSS automatically
- Hot Module Replacement (HMR) support
🚀 Production Build
- Generates optimized CSS at build time
- Only includes utilities used in your code
- No runtime overhead
- Optional production-only class-name mangling with no runtime overhead
How It Works
- The plugin scans files specified in the
contentarray - Extracts utility class names from your code
- Generates CSS for those utilities on-demand
- Outputs to the specified CSS file
- Watches for changes in development mode
Framework Support
Works with all Vite-supported frameworks:
- ⚛️ React
- 🖖 Vue
- 🔺 Astro
- 💎 Solid
- 🔥 Svelte
- 📦 Vanilla JS
Example
Input (your component):
<div className="p-4 bg-blue-500 text-white rounded-lg hover:bg-blue-600">
Hello GustCSS!
</div>Output (src/styles/utility.css):
.p-4 { padding: 1rem; }
.bg-blue-500 { background-color: #3b82f6; }
.text-white { color: #ffffff; }
.rounded-lg { border-radius: 0.5rem; }
.hover\:bg-blue-600:hover { background-color: #2563eb; }Requirements
- Node.js >= 18.0.0
- Vite ^4.0.0 || ^5.0.0 || ^6.0.0
Related Packages
- gustcss - CLI tool
- @gustcss/postcss - PostCSS plugin
License
MIT
