DEV Community

j1ngzoue
j1ngzoue

Posted on

1

Type-safe use of css custom-property in Vite

Introduce

When staring with css modules in react, I often encounter situations where custom properties are used.
When staring with css modules in react, I often encounter situations where custom properties are used.
We have released a tool that solves those problems, and we would like to introduce it to you.
If you are using Vite, you can read and use css-preprocessoroptions.

Repo

https://github.com/activeguild/css-custom-property-extractor

Usage

  • Install the package.
npm i -D css-custom-property-extractor
Enter fullscreen mode Exit fullscreen mode
  • For example. Parsing bootstrap.scss outputs the following typescript file.
npx ccpe -i ./samples/scss/bootstrap.scss
Enter fullscreen mode Exit fullscreen mode

output.

/**
 *  #0d6efd;
 */
export const bsBlue = "var(--bs-blue)"
/**
 *  #6610f2;
 */
export const bsIndigo = "var(--bs-indigo)"
/**
 *  #6f42c1;
 */
export const bsPurple = "var(--bs-purple)"
...
Enter fullscreen mode Exit fullscreen mode
  • Import and use the output typescript file.

At the end

We have shown how to bring custom properties into the TS world and use them in type safety.
In addition to this, please read on to find out how to load styles and use classes in a type-safe manner.
https://dev.to/activeguild/i-made-a-typescript-plugin-for-css-modules-that-can-be-used-with-vite-3ofg
https://dev.to/activeguild/type-safe-development-with-vite-x-react-x-css-modules-x-typescript-1ebc

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more