DEV Community

Daniel Warren
Daniel Warren

Posted on

A Lightweight Package to Generate CSS and JS Variables

Developers love new projects. The blank canvas.

One of my favorite things to do in a new project is setup the theming, thinking about the look and feel of the new application. But the work becomes tedious, and I end up copying and pasting a lot of css and js variables from old projects.

To solve my problem, I created a lightweight, probably too simple, package called varbq, pronounced like barbeque, because, hey, Memorial Day is coming up.

I tend to use the same theme format over and over again, which is very similar to what the amazing book, Refactoring UI, lays out.

Theses projects generally have primary, secondary, accent, and grey colors, each having between five and nine shades, for example, primary200 or accent900. They'll also include spacing sizes to keep the app uniform, like spacing100: 4px, spacing200: 8px, etc. The same goes with typography, shadows, and occasionally screen size.

This is where varbq comes in handy.

After installing, run the command npx varbq build to create the varbq.json file. Passing in optional flags --js or --css only creates those files (for example if it's a React Native project), otherwise both get generated. This command will create a varbq.json file if one doesn't exist.

Each key in the file will create variables based on the array of values, incrementing by 100. So...

{
  "primary": ["hsl(216, 99%, 98%)", "hsl(216, 98%, 92%)", "hsl(216, 95%, 86%)"],
  "spacing": ["4px", "8px", "12px"]
}
Enter fullscreen mode Exit fullscreen mode

becomes...

export const varbq = {
  primary100: "hsl(216, 99%, 98%)",
  primary200: "hsl(216, 98%, 92%)",
  primary300: "hsl(216, 95%, 86%)",
  spacing100: "4px",
  spacing200: "8px",
  spacing300: "12px"
}
Enter fullscreen mode Exit fullscreen mode

and...

:root {
  --primary100: hsl(216, 99%, 98%);
  --primary200: hsl(216, 98%, 92%);
  --primary300: hsl(216, 95%, 86%);
  --spacing100: 4px;
  --spacing200: 8px;
  --spacing300: 12px;
}
Enter fullscreen mode Exit fullscreen mode

The variable files live in varbq/ at the root of the project.

Check out the docs for more information and let me know any features you'd like to see in the future.

Top comments (1)

Collapse
 
ekqt profile image
Hector Sosa

Nice post! At first, I thought this was not a good pattern to define variables outside of the components themselves, but then again it's a great practice to maintain consistency across your project. Specially for those small details like state styling, border, shadows, etc.

I see you enjoy sharing visual content, framing screenshots is a great way to make your content stand out.

We've built a completely free and OSS tool to build engaging screenshots faster. Check it out and let us know what you think! usescreenshot.app/github I'd appreciate if you give it a Star in Github if you find it helpful.