---
page: https://salty-css.dev/concepts/compiler
index: https://salty-css.dev/llms.txt
author: [Teemu Lahjalahti](https://www.linkedin.com/in/teemulahjalahti/)
lastUpdated: 2026-10-01
breadcrumbs: [Concepts](https://salty-css.dev/concepts) / [Compiler & Zero-Runtime](https://salty-css.dev/concepts/compiler)
---
# How Salty CSS compiler achieves zero-runtime, server-first rendering, and what was the reasoning behind .css.ts files

Building Salty CSS had clear goals. Some of them were inspired how others have approached same issues but and couple came from priorizing different DX that others are going for. While some features have come later, the core of the compiler has stayed largely the same as it's first job was to ensure a build pipeline that would output zero-runtime CSS-in-JS.
---
## Towards Zero-Runtime
The shift away from runtime CSS-in-JS wasn’t a matter of taste — it was structural. React Server Components (RSC) and server-first architectures like Astro put real pressure on the model that powered the previous generation of libraries: leaning on React Context and client-side CSSOM injection creates genuine friction in a server-rendered world, where much of your tree never touches a client runtime at all.
That said, the term "zero-runtime" has become heavily diluted. Plenty of frameworks that wear the label still ship meaningful orchestration logic to the client, or ask you to work around the edges of static analysis.
Salty CSS takes a particular path through that space. This page demystifies the "magic" behind the compiler: why Salty CSS asks for specific file extensions, how its execution model differs from AST extraction, and what "zero-runtime" actually means here — including the parts where it isn’t literally zero.
## The Reality of "Zero-Runtime"
To understand Salty CSS, look at what actually ships to the browser.
In a server-first paradigm (like Next.js App Router without `'use client'`, or Astro without `client:load`), **Salty CSS is genuinely zero-runtime**. No style injection, no variant mappers, no theme providers. The HTML arrives with hashed class names, and the static CSS file handles the rest.
But what happens when you *do* need an interactive client component?
Unlike runtime CSS-in-JS, Salty CSS never injects ` next to an element with className={className}
```
Because the same parser runs, JSON-shaped input gets the full Salty surface for free: `{colors.brand}` tokens resolve to the same CSS variables your `styled` components use; `@media`, `&:hover`, and nested selectors all keep working; and two blocks with structurally-identical payloads collapse to a single rule via the shared hash. A CMS block effectively ships "CSS in JSON" and slots straight into your design system — no second pipeline, no escape-hatch global CSS file, and no client styling runtime appearing on the page just because some rules were resolved per-request. The CSS is emitted as a string into the HTML response, and the browser parses it the way it parses your static stylesheet.
Reach for this when content authors want power — give them the parser, not a constrained subset. See the [`defineRuntime` API reference](/react/docs/basics/runtime-styles) for the full surface: signature, feature-support table, scoping, and worked examples.
### Smart Hashing and Deduplication
The compiler uses deterministic hashing (`toHash`). If a `HeroBlock` and a `TextBlock` independently define identical style objects, they generate the exact same hash. The CSS rules are emitted to the final stylesheet only once, automatically deduplicating your output and keeping the CSS payload minimal.
## Execution over Extraction (esbuild vs. AST)
To extract styles at build time, a compiler has to understand your code. There are two broad families for doing this, and they make different tradeoffs.
The first is **Abstract Syntax Tree (AST) static analysis**, used to great effect by tools like Panda CSS (and, historically, by Babel-based extractors like Linaria). These are genuinely impressive pieces of engineering — modern static extractors do identifier resolution, constant folding, and partial evaluation, and they’re fast and battle-tested in large codebases.
The tradeoff is inherent to the approach: the analyzer reasons about your code without running it. When a value can only be known at runtime — a prop driven by state, a token resolved through an indirection the analyzer can’t follow, a style object built by a sufficiently dynamic helper — the extractor has to either skip it or pre-generate every plausible combination ahead of time. That’s why static tools offer escape hatches (Panda’s `staticCss`, for instance) to declare the dynamic surface up front. It’s a perfectly reasonable model; it just asks you to keep your styles statically analyzable, and to reach for those hatches when you can’t.
Salty CSS sits in the other family: **it executes rather than analyzes.** Instead of parsing an AST, the Salty compiler uses `esbuild` to actually evaluate your `.css.ts` files in a Node environment during the build step. This is the same fundamental idea Vanilla Extract pioneered with its `.css.ts` model, and Salty owes it a clear debt.
Because the code is genuinely executed:
- You can safely import variables, functions, or design tokens from anywhere in your codebase.
- You can write complex helper functions to generate style objects.
- You can even use `async/await` inside your style definitions (e.g., fetching a remote design token registry during the build).
If your code runs in Node, Salty CSS can compile it. The cost of this approach is the constraint it places on *where* styles live — which is the subject of the next section — but in exchange you don’t have to keep your styling logic statically legible to a parser.
## The Compilation Pipeline
Knowing *why* Salty CSS executes code rather than parsing ASTs is useful context. Knowing *what actually happens* between saving a file and seeing a styled component in the browser is what you need when something breaks — or when you’re trying to understand why a particular file is slowing your build down.
There are two distinct journeys to trace. The first is the **build-time funnel**: what runs when you start the dev server or kick off a production build. The second is the **load-time funnel**: what the bundler does with a `.css.ts` file when it encounters it as an import, and what the browser ends up with.
### Funnel 1 — Build time: `.css.ts` → `saltygen/index.css`
```text
Plugin hook → Discovery → Config pass → esbuild (per file) → import() → CSS generation → layer assembly → index.css
```
**1. Plugin hook fires**
The bundler plugin (`saltyPlugin` for Vite, the webpack loader, `withSaltyCss` for Next.js) hooks into the bundler’s `buildStart`. It kicks off a full generation, which begins by wiping `saltygen/` clean and recreating its working subdirectories from scratch. Everything flows from this point on a fresh slate.
**2. File discovery**
A recursive walk of the project tree skips `node_modules` and `saltygen/` entirely. A file counts as salty if its name matches `*.(salty|css|styles|styled).(ts|tsx|js|…)`. Within that set, any file that also calls a `defineX(` factory is additionally flagged as a *config file* and queued for processing first. Two sets leave this step: all salty files, and the config-file subset.
> [!NOTE]
> **Perf:** This is a synchronous depth-first filesystem walk across the whole project. In a large monorepo with thousands of directories, the syscall overhead is measurable. The compiler can’t skip arbitrary output directories — only `node_modules` and `saltygen/` are excluded by name. Keep generated directories out of your source tree, and avoid nesting `.css.ts` files inside paths that share a prefix with other deeply populated directories.
>
> Note: performance optimizations are on the roadmap
**3. Config pass (parallel)**
Config files run before anything else — they declare the design tokens and templates that every component file depends on. Each one goes through the same per-file compile step as everything else (see step 4), and its exports are sorted by what they declare: variables, templates, media queries, fonts, imports, and globals. `salty.config.ts` itself is compiled here as well, and its output is merged in.
The output of this pass is written into `saltygen/`: the global CSS layers (variables, reset, global, templates, fonts, imports), the generated TypeScript token/template/media-query types, and a serialised snapshot of the merged config — tokens, templates, media queries — that later steps can read without re-running the compiler.
**4. Per-file esbuild compilation**
This is the step that makes Salty CSS an *execution-based* compiler, and where build performance is most sensitive.
Before esbuild ever sees the source, two things happen to it. First, any `styled(SomeNonSaltyComponent, …)` call is rewritten to `styled('div', …)`, so non-salty components don’t drag their import chains into the bundle. Second, the cached config is made available to the file at evaluation time, so each file can resolve design tokens without re-compiling the config.
The patched source is then fed to **esbuild via stdin** (not as a file on disk), bundled, tree-shaken, and transpiled to a Node-compatible format. The result is written into `saltygen/js/` under a deterministic, content-derived filename — so an unchanged file produces the same path and can be reused by the incremental HMR path.
> [!NOTE]
> **Perf:** esbuild is written in Go and is extremely fast — but it follows every `import` chain in the file. `packages: 'external'` excludes `node_modules`, but *local* barrel files are a different matter. If your design tokens live in `./tokens/index.ts` and that file re-exports 50 individual token modules, esbuild follows all 50 chains for every `.css.ts` that imports it. Each file gets its own esbuild invocation, so a barrel with 50 re-exports across 80 style files means 4 000 extra module parses. Import from the specific token file you need, not a catch-all barrel.
**5. Dynamic `import()` + export bucketing**
The compiled `.js` is loaded into the running Node process with a dynamic `import()`. This is the step that separates Salty CSS from static AST tools: the code is *executed* — any logic you wrote runs, any imports resolve, any `async/await` settles. The exports come back as a live JavaScript object.
Each named export is then inspected to work out what it is — a keyframes definition, a className generator, or a styled generator — and bucketed accordingly. Exports that resolve asynchronously (a bare `Promise`, or a function flagged to be awaited) are settled before they’re bucketed.
> [!NOTE]
> **Perf:** You *can* `await fetch(...)` inside a style definition to pull tokens from a remote registry at build time. Each unresolved `await` serialises evaluation within that file’s module. If 30 components each independently fetch from the same endpoint, you wait for 30 sequential requests. Batch-fetch once in a shared import and let the other files import the result instead — esbuild will inline the value, and the fetch runs once.
**6. CSS generation**
For each generator, the build-time context is locked in: the export name becomes the CSS filename prefix (`Button` → `cl_button-TzHVd-0.css`) and, in development, the value of the `data-component-name` attribute.
The generator then resolves and serialises its styles — which means it:
- Resolves `{token.path}` references to `var(--token-path)` CSS custom properties
- Expands template call sites (`textStyle: 'heading.large'` → the class that the template layer emits)
- Handles `@media` blocks, pseudo-selectors, and modifier rewrites declared in your config
- Serialises the result to a CSS string
The **hash** is computed from the style content itself — base, variants, and compound variants — not from the export name. It’s content-addressed: rename the export and nothing changes; edit a style value and the hash changes. Two components with structurally identical style objects produce the same hash and collapse to a single CSS rule, deduplicated automatically.
> [!NOTE]
> **Note on cascade order:** A `styled()` call whose first argument is another styled component increments `priority` by one. Higher-priority generators land in a later CSS layer (`l1`, `l2`, …). Because the `@layer` order is declared at the top of `index.css`, the cascade is deterministic: a more-specific component’s rules always win over its base’s rules, regardless of where the files live on disk or what order they were compiled in.
**7. Layer assembly + `index.css`**
Component CSS files are grouped by priority and merged into `l_0.css`, `l_1.css`, and so on — each wrapped in `@layer l0 { … }`. Each per-component block is delimited by `/*start:-*/` and `/*end:*/` markers. These markers are how the HMR incremental path patches a single component’s CSS without triggering a full rebuild.
`index.css` is then assembled as the single entry point: a `@layer imports, reset, global, templates, fonts, l0, l1, …;` declaration at the top, followed by `@import` rules for each global file and each layer file. This is the file the user’s app imports.
---
### Funnel 2 — Load time: `saltygen/` → rendered component
The build funnel produces the CSS. This second funnel traces what happens when the bundler processes a `.css.ts` *import* in your component tree, and what the browser ultimately receives.
```text
Bundler load hook → source transform → minified client file → browser renders
```
**1. Bundler load hook**
When the bundler encounters a `.css.ts` import, the plugin’s `load` hook fires. For React projects it runs a framework-specific transform that is loaded lazily and memoised for the entire bundler session, so the transform module loads once regardless of how many salty files exist.
**2. Source transform**
The per-file compile step runs again on the file (reusing the cached `.js` from `saltygen/js/` if the content hasn’t changed). For each styled or className export, the generator’s pre-computed client metadata is serialised — `{ hash, variantKeys, propValueKeys, defaultProps, attr }` — and the source is rewritten in place: the full style object is replaced with the baked-in client form.
```ts
// Your source
export const Button = styled("button", {
base: { padding: "{spacing.medium}" },
variants: { intent: { primary: { background: "{theme.primary}" } } },
});
```
```ts
// What the bundler serves to the browser
export const Button = styled("button", "TzHVd", {
hash: "TzHVd",
variantKeys: ["intent"],
propValueKeys: [],
defaultProps: {},
attr: { "data-component-name": "Button" }, // stripped in production
});
```
Import paths are also rewritten: `{ styled } from "@salty-css/react/styled"` becomes `{ styledClient as styled } from "@salty-css/react/styled-client"`. All style logic — the `base` object, token references, variant definitions — is gone from the bundle.
**3. Browser receives**
The client bundle contains no CSS serialisation engine, no CSSOM injection, no theme provider. The HTML element carries hashed class names (`class="TzHVd intent-primary"`). The static `saltygen/index.css` — already linked in `` — provides `.TzHVd { … }` and `.TzHVd.intent-primary { … }`. The browser applies them via its native cascade. Nothing computes anything.
**4. React render — server-first path**
In a React Server Component or an Astro component, there is no client bundle for that component at all. `styledClient` runs on the server, emits a string of class names baked into the HTML, and the component contributes zero JavaScript to the client payload. This is the "genuinely zero-runtime" case from the opening of this page.
**5. React render — client component path**
`styledClient` is the thin mapper that ships to the browser when you mark a component `'use client'`. It receives the pre-compiled client metadata, reads variant props at render time (e.g. `intent="primary"`), and appends the matching class name alongside the base hash class. If any `css-*` props are present (like `css-bg-color="tomato"`), it writes the corresponding CSS custom property as an inline style. No new classes are generated, no `