How to Use CSS Bundling in Remix for Efficient Styling
In Remix, use the
links export in your route modules to include CSS files, and Remix automatically bundles them for you. You can import CSS files directly and return them in links to enable efficient CSS bundling and loading.Syntax
To bundle CSS in Remix, you export a links function from your route module. This function returns an array of objects, each with a rel and href property. The href points to the imported CSS file, and Remix bundles these CSS files automatically.
You import your CSS file as a module and then reference it in links.
javascript
import stylesUrl from "./styles.css"; export function links() { return [{ rel: "stylesheet", href: stylesUrl }]; }
Example
This example shows a Remix route component that imports a CSS file and uses the links export to bundle and apply the styles.
javascript
import stylesUrl from "./styles.css"; export function links() { return [{ rel: "stylesheet", href: stylesUrl }]; } export default function Example() { return <div className="container">Hello, styled Remix!</div>; }
Output
<div class="container">Hello, styled Remix!</div>
Common Pitfalls
- Forgetting to export the
linksfunction means your CSS won't load. - Not importing the CSS file correctly will cause errors or missing styles.
- Using global CSS without proper scoping can cause style conflicts.
- Trying to import CSS in non-route modules won't bundle styles automatically.
javascript
/* Wrong: No links export, styles won't load */ import "./styles.css"; export default function NoStyles() { return <div>Missing styles</div>; } /* Right: Export links with imported CSS */ import stylesUrl from "./styles.css"; export function links() { return [{ rel: "stylesheet", href: stylesUrl }]; } export default function WithStyles() { return <div className="container">Styled content</div>; }
Quick Reference
- Import CSS file:
import stylesUrl from "./styles.css"; - Export links function:
export function links() { return [{ rel: "stylesheet", href: stylesUrl }]; } - Use CSS classes in JSX:
<div className="className"></div> - Remix bundles CSS automatically for all linked stylesheets.
Key Takeaways
Always export a links function returning your CSS imports to enable bundling.
Import CSS files as modules and reference them in links for automatic bundling.
CSS bundling in Remix improves load speed by combining stylesheets.
Avoid importing CSS outside route modules to ensure proper bundling.
Use className in JSX to apply bundled CSS styles correctly.