Import CSS Modules into Bun for server rendered html/components
npm install bun-css-modulesAllows you to import CSS Modules directly into Bun.
This loader uses the incredibly fast Rust based Lightning CSS under the hood.
To install dependencies:
``bash`
bun add -D bun-css-modules
Create cssLoader.ts:
`ts
import { plugin } from 'bun'
import { moduleCssLoader } from 'bun-css-modules'
plugin(moduleCssLoader())
`
You can pass in options to customize some settings via moduleCssLoader({ [optionName]: . The defaults are:
`js`
{
filePattern = /\.module.css$/,
browserlistQuery = [
'last 4 chrome version',
'last 4 firefox version',
'last 2 safari version',
],
}
Create a bunfig.toml if you don't have one and add:
`toml`
preload = ["./cssLoader.ts"]
Example using Hono JSX:
`css
/ Button.module.css /
.buttonBase {
appearance: none;
font-family: inherit;
font-size: inherit;
color: inherit;
border-radius: 4px;
}
.primary {
composes: buttonBase;
background: blue;
color: white;
border: 1px solid purple;
}
`
`jsx
import styles from './Button.module.css'
export function PrimaryButton({ children }) {
return
}
`
Include styles once in your head via the special cssText property.
`jsx
import buttonStyles from 'src/components/Button/Button.module.css'
import tableStyles from 'src/components/Table/Table.module.css'
export function Layout({ title, children }: LayoutProps) {
return (
`jsx
import { PrimaryButton } from 'src/components/Button'
import styles from './SignUpPage.module.css'function SignUpPage() {
return (
Sign up
Sign up
{/ One-off page styling can just be included here /}
)
}
`Typescript
Add an ambient file if you don't have one, e.g.
app.d.ts:`ts
declare module '*.module.css' {
const styles: {
cssText: string
[className: string]: string
}
export default styles
}
`And include it in your
tsconfig.json:`json
{
"compilerOptions": {
"esModuleInterop": true,
"strict": true,
"baseUrl": ".",
"types": ["bun-types", "./app.d.ts"]
}
}
``