LoginSignup
4
2

More than 1 year has passed since last update.

💭 始めに

KWCのフロントエンドエンジニアの@eri2490です。
React(Preact)で利用できるスタイリングの比較・導入の検討を行いました。

⛑ CSS in JSとは?

特定のフレームワークやライブラリを指すものでは無く、「JavaScriptの中でCSSを書く」という概念のことです。JS実行時にスタイルを処理し、HTMLのheadにスクリプトを追加します。
他にはCSS-Modulesや、直接cssファイルを読み込む手法があります。今回はJSファイルに直接CSSも書く方法を取りたかったので、CSS in JSのライブラリの比較も行いました。

🏋🏼 npm trendsでの比較

候補にあがったライブラリ
1. styled-component
2. emotion
3. JSS
4. goober
5. Picostyle
Screen Shot 2021-12-22 at 16.21.00.png
styled-component のダウンロード数の多さとemotion の一定の人気・パッケージサイズの軽量さが特徴的でした。
一方でPicostyleはダウンロード数・スター数の少なさから、検討することを止めました。

🛹 インポートや書き方の比較

emotion は複数の書き方が提供されており、styled-componentgoober はStyled Componentを作成します。
JSS はCSSのクラスを作成し、classNameで指定します。

styled-component

import styled from 'styled-components';

const TitleComponent = () => {
    return <Title>title component</Title>;
};

const Title = styled.h1`
    color: 'red';
`;

emotion

// styled-componentっぽく
import styled from '@emotion/styled';

const Title = () => <Text>title component</Text>;

const Text = styled.h1`
  color: red;
`;
// Object Styles
import { css } from '@emotion/css';

const Title = () => <h1 className={Text}>title component</h1>;

const Text = css({
    color: 'red',
});
// Object Stylesを変形してJSSっぽく
import { css } from '@emotion/css';

const Title = () => <h1 className={styles.title}>title component</h1>;

const styles = {
  title: css({
    color: 'red',
  }),
};

JSS

import { createUseStyles } from 'react-jss';

const Title = () => {
    const classes = styles();
    return (
        <h1 className={classes.text}>title component</h1>
    );
};

const styles = createUseStyles({
    text: {
        color: 'blue',
    }
});

goober

import { styled } from 'goober';

const TitleComponent = () => <Title>title component</Title>;

const Title = styled('h1')`
    font-size: 3rem;
    margin-bottom: 0.8rem;
`;

🎄 まとめ

Styled Componentを作成すると生のCSSを書けるという利点はあるものの、IDEでCSSの補完が効かない点や、一見して普通のコンポーネントかどうかわからないという点はデメリットに思えました。
逆にCSSクラスを作成する場合は上記の書きづらさは解消される一方で、定義されたプロパティのみしか使えないという点で、困難さが予想されます。

個人的にはパッケージサイズが小さく、IDEでCSSの補完が効く書き方ができるemotionの使い勝手が良さそうでした。

🍻 We're hiring!

KWCでは、エンジニアを募集しています。
https://recruit.kddi-webcommunications.co.jp/recruitment/career/
ご興味を持たれた方はぜひご連絡をお待ちしております!
それでは良いお年をお迎えください🎍

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2