TLDR: Using a Gatsby starter setup I investigated four CSS-in-JS libraries, Emotionstyled-componentsTreat and JSS. In this comparison I summarise the differences in setup, documentation, styling paradigm and Node package size. The libraries are all very similar and essentially up doing the same thing, but in different ways. Treat has the smallest bundle size with JSS the largest. Styled-components is the most popular with Treat the least. Using styled-components is the safest way to get started, but, Treat may be worth a gamble based on its scalability and bundle size.

The hack

HTML in JavaScript, are you sure? CSS in JavaScript? Now I know you’re having a laugh!

A few years ago if someone mentioned writing HTML in JavaScript as a way of building large scale websites, I would have laughed it off as some sort of crazy idea. Now, with React, writing markup as part of a component’s render function is second nature.

For me, it has been the same with CSS. I heard about the move to code CSS into components a while ago and the thought made me cringe. Surely, these are completely different languages and mixing them is just asking for trouble.

However, recently I’ve taken more of an interest. During a recent hackathon, I experimented with four libraries I came across:

  • Emotion
  • Styled-components
  • Treat
  • JSS

Findings

Emotion (64.82kb)

Emotion is a library designed for writing css styles with JavaScript. It provides powerful and predictable style composition in addition to a great developer experience with features such as source maps, labels, and testing utilities. Both string and object styles are supported.

Setup

Straightforward installation with optional extras for styled CSS and React (which are separate packages). The core package gives developers access to the css prop to add styles.

	import { css } from '@emotion/core';

	const style = css`
	    color: hotpink;
	`
	const SomeComponent = ({ children }) => (
	    <div css={style}>
	        Some hotpink text.
	        {children}
	    </div>
	)

Optional extras include @emotion/styled package allowing components to have styles attached to them.

#software-engineering #javascript #comparison #styled-components #css #programming

CSS-in-JS: An Investigation
1.45 GEEK