Trousers

Next.js

In an App Router project, use esbuild to compile a style module before Next.js starts. The app imports the resulting styles and stylesheet, and uses classnames with Next.js’s React JSX setup. This example renders the box in a Server Component.

Compile the styles

sh
npm install trousers
npm install -D esbuild @trousers/esbuild

Create styles/box.js with the styles and spacing choices.

js
import { css } from 'trousers';

export const box = css('box', { backgroundColor: '#fff1ed', borderRadius: 8 })
    .variant('inset', {
        s: { padding: 4 },
        m: { padding: 8 },
        l: { padding: 16 },
    });

Add scripts/build-styles.mjs to emit the module and stylesheet.

js
import { build } from 'esbuild';
import trousers from '@trousers/esbuild';

await build({
    entryPoints: ['styles/box.js'],
    bundle: true,
    format: 'esm',
    packages: 'external',
    outfile: 'generated/box.mjs',
    plugins: [trousers()],
});

In package.json, run the script before next dev and next build. Add generated/ to .gitignore. During development, rerun node scripts/build-styles.mjs after editing styles/box.js.

json
{
    "scripts": {
        "dev": "node scripts/build-styles.mjs && next dev",
        "build": "node scripts/build-styles.mjs && next build"
    }
}

Use the styles in the App Router

Import generated/box.css in app/layout.jsx to make the stylesheet available to the app. Next.js global CSS

jsx
import '../generated/box.css';

export default function RootLayout({ children }) {
    return <html lang="en"><body>{children}</body></html>;
}

In app/page.jsx, import the compiled module and select a variant with classnames.

jsx
import { classnames } from 'trousers';
import { box } from '../generated/box.mjs';

export default function Page() {
    return <main className={classnames(box, { inset: 'm' })}>Hello from Next.js</main>;
}

Next.js includes the classes in the rendered HTML and serves the extracted stylesheet. This pipeline compiles the style module separately, so all of its exported styles are included in the stylesheet. Keep the entry focused on styles used by the app.