Our great sponsors
-
SurveyJS
Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App. With SurveyJS form UI libraries, you can build and style forms in a fully-integrated drag & drop form builder, render them in your JS app, and store form submission data in any backend, inc. PHP, ASP.NET Core, and Node.js.
-
vite-plugin-sass-dts
This is a plugin that automatically creates a type file when using the CSS module type-safely.
-
timjames.dev
Personal site for Tim W James - Portfolio, Blog, and more. Built with TypeScript, React and Vite. Deployed to timjames.dev
-
InfluxDB
Power Real-Time Data Analytics at Scale. Get real-time insights from all types of time series data with InfluxDB. Ingest, query, and analyze billions of data points in real-time with unbounded cardinality.
Minimal repo with this configured: https://github.com/Tim-W-James/typed-tailwind-and-scss-modules
First we need to generate types. For Tailwind, we can do this using postcss-ts-classnames, which essentially creates a big union type of all the classes it finds in the bundled app. Importantly, this happens after unused classes are purged, so we don't get the entire list of possible Tailwind classes. This is ideal for performance reasons, but does mean there is a small lag between a class being used in code and the generated types being updated.
To generate types for SCSS modules, we use vite-plugin-sass-dts. We simply need to add this to our list of Vite plugins:
To use the global Tailwind types from styles/cssClasses.d.ts, I've leveraged a lot of work from this post, so credit goes there for a lot of the complex TypeScript wizardry that makes things work. In essence, it builds upon the classnames (or clsx) to provide a helper function that gives us with the type safety we're after. This cleverness means we get type checking that works with whitespace, multiple classes (e.g., "container p-5")and arbitrary values (e.g., "border-[5px]"). The input "container p-5 invalid-class" provides the nifty error message:
The source code for my website uses this extensively: https://github.com/Tim-W-James/timjames.dev
Applying classes directly to a React component provides no type safety by default. This can lead to errors, unexpectedly missing styles, and a lesser development experience without intellisense. In this blog, I'll be achieving type safety for both Tailwind and SCSS (Sass) Modules.
Applying classes directly to a React component provides no type safety by default. This can lead to errors, unexpectedly missing styles, and a lesser development experience without intellisense. In this blog, I'll be achieving type safety for both Tailwind and SCSS (Sass) Modules.