danieldelcore/trousers
About
hooks-first CSS-in-JS library, focused on semantics and runtime performance
Web & App DevelopmentMeasured star growth
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- 0
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
Original
Trousers 👖
Documentation · API reference · Storybook
Write React styles as objects. Trousers compiles them into regular CSS with esbuild and applies the resulting class names through the css prop or styled. Use modifiers for predefined states, CSS custom properties for themes, and React's style prop for runtime values.
Motivation · Setup · Styles and modifiers · Using className · Themes and globals · Server rendering · Performance · Development
Motivation
When a button becomes primary, its background, text color, and hover treatment might all change together. A primary modifier puts those declarations in one place. Reading the styles tells you what changes, and reading the component tells you when it changes. That idea comes from BEM's use of named modifiers to make a component's visual states explicit.
Trousers carries those groups into the stylesheet. The base style and each modifier have their own class, and every instance of the component shares those rules. esbuild writes the stylesheet at build time. At runtime, components choose which classes to apply and the browser handles the cascade.
Static style objects make extraction possible. Predefined variants such as primary and disabled belong in modifiers, theme values can flow through CSS custom properties, and values known only at runtime, such as the width of a progress bar, go through the style prop.
For the original motivation behind Trousers, see CSS-in-JS: What happened to readability?.
Setup
npm install trousers @trousers/react react react-dom
npm install --save-dev @trousers/esbuild esbuild
import { build } from 'esbuild';
import trousers from '@trousers/esbuild';
await build({
entryPoints: ['src/app.tsx'],
outdir: 'public',
bundle: true,
jsx: 'automatic',
jsxImportSource: '@trousers/react',
plugins: [trousers()],
});
Load the stylesheet emitted for the entry in your HTML alongside the JavaScript.
<link rel="stylesheet" href="/app.css" />
<script src="/app.js" defer></script>
For hashed filenames or multiple entries, enable metafile: true and read the JavaScript entry's cssBundle field when generating HTML. See esbuild's CSS bundling documentation.
For TypeScript, set "jsx": "react-jsx" and "jsxImportSource": "@trousers/react" under compilerOptions. The classic JSX factory is also available from @trousers/react.
Styles and modifiers
import { css } from 'trousers';
const button = css('button', {
padding: '8px 12px',
color: '#223',
':hover': { textDecoration: 'underline' },
'@media (min-width: 768px)': {
padding: '12px 20px',
},
}).modifier('primary', {
color: 'white',
backgroundColor: '#1456b7',
});
export function Button({
primary,
width,
}: {
primary: boolean;
width: number;
}) {
return (
<button css={button} $primary={primary} style={{ width }}>
Save
</button>
);
}
- Import
cssdirectly fromtrousersor@trousers/react, or as the default import from@trousers/core. The first argument can be an optional string for readable class names. - Write style objects directly in
css(),.modifier(),.variant(),.theme(), and.global(). Static strings, numbers, nested objects, fallback arrays, andnullare supported. Use CSS strings such as'2rem'for explicit units and'"Label"'for quotedcontent. Pass runtime values through React'sstyleprop. - The bundler reports an error at the source for boolean or function values, including inside nested rules and fallback arrays. Pass booleans as modifier flags. Compute per-instance values in the component and pass them through
style. - Use
&to refer to the scoped selector. A leading pseudo-selector attaches to the current selector, and a plain selector targets descendants. - Nonzero numeric lengths get
px. Unitless properties and CSS custom properties retain their numeric values. Supply a string for other CSS units. - Modifier props such as
$primarytoggle classes. When matching declarations have the same specificity, later modifiers in the chain take precedence.
Toggling modifiers with booleans
A modifier declared with .modifier('primary', ...) is off by default. Pass true to apply it or pass false to keep the base styles. Use props or state for the boolean and keep the modifier's style object static.
All three examples use the button style defined above.
// With standard React JSX, use the modifier name as the key.
<button className={classnames(button, { primary: isPrimary })}>Save</button>;
// With the Trousers JSX runtime, use a $-prefixed prop.
<button css={button} $primary={isPrimary}>Save</button>;
// A styled component takes the same $-prefixed prop.
const SaveButton = styled.button(button);
<SaveButton $primary={isPrimary}>Save</SaveButton>;
Import classnames and styled from trousers. In JSX, $primary is shorthand for $primary={true}.
Using className
Keep your existing React JSX runtime and use classnames to resolve compiled styles into a string. Keep the esbuild plugin and load the emitted stylesheet as usual.
import { classnames, css } from 'trousers';
const button = css({ color: 'navy' }).modifier('primary', { color: 'white' });
export function Button({
primary,
width,
}: {
primary: boolean;
width: number;
}) {
return (
<button className={classnames(button, { primary })} style={{ width }}>
Save
</button>
);
}
Pass modifier names without the JSX prop prefix, such as primary. The result includes the base and theme classes and any active modifiers, in declaration order within each group. The returned string can be combined with consumer classes using a utility such as clsx. The helper is also exported by @trousers/core for framework-neutral consumers.
Named variants
Use .variant() for mutually exclusive choices, such as a Box with optional inner spacing. Define each choice as a static style object. An omitted choice leaves the base styles in place. Boolean modifiers can be used alongside variants.
import type { ReactNode } from 'react';
import { css, styled } from 'trousers';
const box = css({ minHeight: 20 }).variant('inset', {
s: { padding: 4 },
m: { padding: 8 },
l: { padding: 16 },
});
const BoxFrame = styled.div(box);
function Box({ inset, width, children }: {
inset?: 's' | 'm' | 'l';
width?: string;
children?: ReactNode;
}) {
return <BoxFrame $inset={inset} style={{ width }}>{children}</BoxFrame>;
}
With the Trousers JSX runtime, use <div css={box} $inset={inset}>. With standard React JSX, import classnames and use <div className={classnames(box, { inset })}>. Trousers infers the named choices for styled and classnames. On plain JSX elements, $ props accept booleans and strings.
Themes and globals
import { css, styled } from 'trousers';
const light = css({}).theme({
color: { accent: '#1456b7' },
});
const page = css({}).global({
body: { margin: 0, fontFamily: 'system-ui' },
});
const Link = styled.a(css({ color: 'var(--color-accent)' }));
export function App() {
return (
<main css={light}>
<section css={page}>
<Link href="/settings">Settings</Link>
</section>
</main>
);
}
Theme objects become CSS custom properties on the element and inherit through its descendants. Global rules apply across the page while the generated stylesheet is loaded. Use unique names for global constructs such as @keyframes.
Server rendering
Build the server with the same JSX settings as the client, set platform: 'node', and use trousers({ emitCss: false }). Put the client build's stylesheet in the server-rendered <head>. The same style chain produces the same classes on both sides, so React can hydrate the existing markup.
Performance
Trousers emits one class per nonempty base, modifier, or theme block. A single class can cover several declarations, nested selectors, and media queries. Reusing that style on more elements leaves the stylesheet size unchanged. React resolves the class list from the css and modifier props. The browser handles the cascade, and React applies runtime values through its normal style prop.
These measurements use esbuild 0.25.12 and gzip level 9. They cover the CSS emitted for two examples in this repository.
| Entry | CSS | Minified CSS | Minified + gzip |
|---|---|---|---|
| Interactive demo | 653 B | 514 B | 309 B |
| Basic stories | 3,218 B | 2,610 B | 697 B |
- Enable
minify: truefor production and serve compressed CSS. Use esbuild'smetafileto track stylesheet size by entry. - The plugin uses an esbuild analysis pass to remove scoped styles that are unused across the build, even when their module has other live exports. A live style keeps all its modifiers because runtime props can activate them.
- Global rules and blocks with document-level at-rules such as
@keyframesretain their cascade order. A style module shared by multiple entries keeps the rules needed by any of those entries. Use separate style modules when pages need fully independent stylesheets. - The analysis pass adds build work and runs companion esbuild plugins a second time. Set esbuild's
treeShaking: falseto emit all styles from bundled modules in one pass. Builds usingtrousers({ emitCss: false })also use one pass.
Entry-specific stylesheets
Use buildEntries for independently deployed pages. It gives each entry its own output directory and removes scoped CSS used only by another page.
import { buildEntries } from '@trousers/esbuild';
await buildEntries({
entryPoints: { home: 'src/home.tsx', settings: 'src/settings.tsx' },
outdir: 'public',
jsx: 'automatic',
jsxImportSource: '@trousers/react',
});
The home and settings pages load /home/home.css and /settings/settings.css respectively. Each entry can split its own lazy imports. Independent builds can duplicate JavaScript shared across pages. A single esbuild build with the plugin shares JavaScript across entries when splitting is enabled and keeps the CSS union for shared style modules.
Debugging generated CSS
Enable esbuild's sourcemap option to trace generated rules to their style objects. Trousers also maps generated CSS errors and warnings in the JavaScript build result to the source style block.
Run yarn benchmark:esbuild after building the packages to measure a cold build and a rebuild after an entry edit. The plugin's onProfile callback provides analysis time, total time, parsed files, and cache hits. Watch builds reuse compiled style objects when their source is unchanged.
Rolldown
Use @trousers/rolldown to extract the same static style objects with the Oxc-based Rolldown bundler. The plugin emits trousers.css for the build's entries and lazy chunks. Include it in your HTML alongside the JavaScript entry.
Bundler benchmark
Both adapters used the same Rust compiler and the same TSX workload, with one plain TypeScript module for every two styled modules. The results are medians of three runs on macOS arm64 with Node 22.18.0, esbuild 0.25.12, and Rolldown 1.3.4.
| Styled modules | esbuild cold | Rolldown cold | esbuild style edit | Rolldown style edit |
|---|---|---|---|---|
| 200 | 76 ms | 28 ms | 54 ms | 29 ms |
| 1,000 | 302 ms | 126 ms | 245 ms | 120 ms |
| 2,500 | 774 ms | 323 ms | 628 ms | 375 ms |
Cold builds produced output in memory. Rebuilds changed one style and wrote output to disk, with file-watcher detection time excluded. Minification and source maps were disabled during timing. Both adapters produced byte-identical CSS after normalization, before and after each edit. esbuild processes CSS through its bundler, while the standalone Rolldown adapter emits it as an asset. Rolldown’s CSS support notes
Run yarn build and yarn benchmark:bundlers to reproduce the comparison. Add module counts, such as yarn benchmark:bundlers 200 1000, to measure specific sizes.
Migrating from the v4 Babel macro
Use the esbuild plugin in place of @trousers/macro and include the emitted CSS in your HTML. Import css from trousers or @trousers/react. Define style objects and their modifier, global, or theme calls in a single chain. Move interpolated values to style.
Rust compiler
The compiler lives in crates/compiler and uses Oxc to parse JavaScript and TypeScript. It resolves the css import, reads static style values, and emits CSS, class metadata, and source offsets. The Node-API addon in crates/node exposes that compiler through @trousers/compiler to the esbuild and Rolldown plugins. Each bundler adapter handles its integration with the bundle graph, tree shaking, source maps, and rebuilds.
The release workflow packages native binaries for macOS, glibc Linux, and Windows on x64 and arm64. Consumers on those targets install the plugin through npm and load the matching binary. A musl Linux checkout can build the addon with RUSTFLAGS="-C target-feature=-crt-static" yarn build:native using a musl toolchain.
Development
Use Node.js 22 and Rust 1.94 or later for development. Run yarn install --frozen-lockfile, then yarn validate to build the packages, compile the stories, type-check and lint source and stories, run tests, and bundle the demo. Run yarn start to serve the demo on port 9000.
Run yarn start:stories to compile the demos with esbuild and open Storybook on port 6006. The Classnames group covers composing conditional styles and switching themes. Edge cases demonstrates the standard React JSX runtime with classnames, inline custom properties, container queries, fallback values, and cascade layers.
Edit the site guides in docs/content. Run yarn docs:build to type-check the sources and generate the API reference and HTML, then yarn docs:preview to preview the site. CI publishes the docs under /trousers/docs/ alongside Storybook at /trousers/. Set the repository's Pages source to GitHub Actions.
Run yarn rust:check for Rust formatting, Clippy, and unit tests. Run yarn build:native to rebuild only the native addon. Run yarn stories:build for a static Storybook build after building the packages. CI also packs the packages and installs them into isolated consumer fixtures to check exported types and hydrate an app using React 17, 18, or 19. Run yarn test:packed 19 after building to reproduce that check locally.
Explore related projects
Loading…