An intro to Panda CSS
Should you consider switching?
The CSS landscape is constantly changing. Five or more years ago, runtime CSS-in-JS libraries like styled-components and Emotion were all the rage, because we were running our apps mostly on the client. However, nowadays in the world of Server Side Rendering (SRR) it's all Tailwind. Or so it would seem. You may be thinking that there are no options remaining for you if you like writing actual CSS, but you'd be wrong. You can of course use ordinary CSS modules - they still work great and never went away. However, if you prefer your CSS with the type safety provided by TypeScript, there are modern CSS-in-JS libraries available like Vanilla Extract, Stitches and Panda CSS. I've been learning about Panda CSS lately, so I thought I'd write a quick intro for anyone who might be interested in trying this out.
What is Panda CSS?
Other than having a cute name, Panda CSS is a build time CSS-in-JS library. Let's break down what that means. CSS-in-JS is a technology that allows developers to write their CSS alongside their JavaScript code. No more separate CSS files with all the CSS rules in them - styles are defined right in your JavaScript. Years ago this would have been considered heresy (separation of concerns!), but JSX changed all that and nobody bats an eyelid at not keeping our concerns separated any longer.
As for the "build time" part, this is different to libraries like styled components, which are run time CSS-in-JS libraries. In Panda CSS, all the CSS is generated at build time and injected into the HTML, meaning it's there ready to go when a user loads the page. In contrast, run time CSS-in-JS libraries generate the CSS when the user loads the app, which means a lot of heavy lifting is done by the browser which can cause performance issues if you're not careful.
How do you install it?
Because Panda CSS is a build time tool, we want to install it as a dev dependency:
npm install -D @pandacss/devOnce that's done, Panda provides a CLI command that will initialise your project for you:
npx panda initThis will create a panda.config.ts file and update your .gitignore file to include the styled-system directory (we'll cover these in more detail later).
Now you'll want to add a prepare script to your package.json file as follows:
"scripts": {
"prepare": "panda codegen",
}You'll want to run this script now that it's in:
npm run prepareThis will create a styled-system directory (more on this later). This is where your generated CSS will end up. In order to load in the generated CSS, add an import to styles.css at the root of your app:
import "../styled-system/styles.css";
function App() {
return <div>This is my app</div>;
}
