Type safe CSS Modules with Flow

Kenneth Skovhus
HackerNoon.com
3 min readJun 20, 2017

--

CSS Modules + Flow = type safety and editor autocompletion

I’ve been dreaming about type safety and editor autocompletion when using CSS Modules. There are a few TypeScript tools for this (see this and this), but I didn’t find any solid tools for Flow.

TL;DR I’ve made some new tools, and when trying them on a codebase I’m working on, Flow found a lot of dead code (and potential bugs)😬

The problems

It is quite easy to misspell a class name or forget to update .js consumers after removing a class in a .css file. As an example, the class foo might not be defined in Button.css:

Solutions

To teach Flow about CSS Modules file, we can create a definition file Button.css.flow containing the class names exposed by Button.css. By doing so we can get:

  • static type checks showing usage of non existing classes
  • editor autocompletion of CSS classes (for editors supporting Flow)

To generate these .flow files I was thinking of two use cases. One using a simple CLI and another using webpack.

Solution: CLI

css-modules-flow-types-cli is a CLI that quickly generates .flow files.

Let us install it:

And then just run the CLI on your source directory:

I recommend using the CLI on your CI system (like Travis or Circle) to ensure that all .flow files are up-to-date before running Flow. This will catch potential styling errors before deploying.

Another use case is quick feedback loop when developing and changing CSS Modules files. The CLI includes a watch mode for this, but I myself would like to avoid having yet another tool that needs to be running while developing. As a lot of people already have webpack running, I did a small loader consuming the tokens from style-loader.

Solution: webpack loader

css-modules-flow-types-loader is a webpack loader keeping .flow files updated by consuming the tokens from style-loader. I recommend using this when developing as part of a webpack-dev-server setup. It will give a small slowdown, as the loader potentially needs write a lot of files.

To get started:

Then update your webpack config:

And then sit back and enjoy CSS Modules being type checked by Flow. 🍺

Please let me know what you think… And give a little ⭐️ over at github.

Hacker Noon is how hackers start their afternoons. We’re a part of the @AMI family. We are now accepting submissions and happy to discuss advertising & sponsorship opportunities.

If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!

--

--

Kenneth Skovhus
HackerNoon.com

Dad, feminist, software engineer. Flipping bits to fight climate change at https://www.tmrow.com/ — Content moved to https://skovhus.github.io/