21 Followers
·
Follow

CSS Modules Next (Intro)

Write CSS however you want without compromising the final CSS file size!

First a bit about the popular CSS Modules. CSS Modules generates unique scoped class names such as .app-components-button-__root--3vvFf. This can be customized to have a shorter name but it still impacts the output CSS file. CSS Modules can also be combined with React using babel-plugin-react-css-modules. It transforms your JSX <div styleName="button" /> to something like <div className="unique_class" /> .

CSS Modules Next inherits the same unique scoping property but in a more optimized way so the output CSS file becomes smaller in large projects! CSS Modules Next makes use of “Atomic CSS” class name generation which can be seen in CSS-In-JS libraries such as Fela and Styletron. Ryan Tsao’s blog post explains this concept very well. It generates a unique class name for each and every CSS declaration. For example:

// styles.scss
.foo {
height: 200px;
width: 100px;
background-color: red;
}
.bar {
height: 200px;
width: 50px;
background-color: red;
}
// Final output (styles.css):
.a { height: 200px; }
.b { width: 100px; }
.c { background-color: red; }
.d { width: 50px; }

Redundant declarations like height and background-color in this case get reused. Now, this is what happens to your JSX:

// Before transpilation:
<div styleName="foo">
<div styleName="bar"></div>
</div>
// After transpilation:
<div className="a b c">
<div className="a c d"></div>
</div>

For both the outer and inner div we are reusing a and c. Imagine a large code-base reusing styles like this!

Differences to CSS Modules/babel-plugin-react-css-modules:

  • It is a custom Typescript transformer for now. (a babel-plugin version may happen in the future)
  • Only anonymous styleName resolution e.g. import ‘./foo.css’
  • Preprocessors supported: Stylus and SASS
  • Outputs a minified and a prettified CSS file (styles.css and styles.min.css respectively) depending on the specified path
  • Supports optional autoprefix
  • One need to specify global file paths for styles that are not in the same folder as your current style
  • Runtime helper function is very small! (100 bytes compared to 900 bytes minified)
  • Compatible with FuseBox but Webpack support is still work in progress.

CSS Modules Next inherits the same ideas from CSS Modules but uses “Atomic CSS” class generation to output a smaller CSS file. Large projects will benefit heavily from this kind of optimization.

Check it out: https://github.com/deamme/ts-transform-css-modules-next.

Written by

Making Open Source contributions ⚡️

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store