LoginSignup
5
1

More than 1 year has passed since last update.

【React・Next.js】emotion/react のセットアップ

Posted at

概要

CRA(Create React App)で作成したReactプロジェクトと、Next.jsプロジェクトそれぞれに対して、emotion/reactの導入方法をまとめました。

どちらもゴールは、.tsxファイルに以下のプラグマを書かなくて済む設定にすることです。

/** @jsx jsx */
/** @jsxImportSource @emotion/react */

emotionは、CSS in JS記法で書くスタイリングパッケージです。

CRA(Create React App)への導入

以下の記事の抜粋になっています。
パッケージについて詳しく知りたい方は、こちらも併せて参照してください。

プロジェクト作成

適当なプロジェクトフォルダを作成して、以下を実行します。

npx create-react-app . --template typescript --use-npm

パッケージインストール

以下をインストールします。

npm i @emotion/react
npm i -D @emotion/babel-plugin
npm i @craco/craco

tsconfig.json

設定を追加します。

tsconfig.json
"compilerOptions": {
    "jsxImportSource": "@emotion/react"
}

craco.config.js

ルート直下にcraco.config.jsを作成して、以下を記述します。

craco.config.js
module.exports = {
  babel: {
    presets: [
      [
        "@babel/preset-react",
        { runtime: "automatic", importSource: "@emotion/react" },
      ],
    ],
    plugins: ["@emotion/babel-plugin"],
  },
};

package.json

内容を修正します。

package.json
"scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test"
}

動作確認

cssプロパティが使用できて、デバッグ(npm start)したときと、ビルド(npm run buildserve -s build)したときにスタイルが反映されていればOKです。

App.tsx
import React, { VFC } from 'react';
import { css } from '@emotion/react';

export const App: VFC = () => {
    return (
        <div css={styles.container}>
            <div css={styles.text}>Hello</div>
        </div>
    )
}

const styles = {
    container: css`
        position: relative;
        width: 100vw;
        height: 100vh;
        background-color: #1e1e1e;
        display: flex;
        justify-content: center;
        align-items: center;
    `,
    text: css`
        font-size: 5rem;
        color: #fff;
    `
}

Next.js への導入

以下の記事の抜粋になっています。
パッケージについて詳しく知りたい方は、こちらも併せて参照してください。

プロジェクト作成

適当なプロジェクトフォルダを作成して、以下を実行します。

npx create-next-app . --ts --use-npm

パッケージインストール

以下をインストールします。

npm i @emotion/react
npm i -D @emotion/babel-plugin

tsconfig.json

設定を追加します。

tsconfig.json
"compilerOptions": {
    "jsxImportSource": "@emotion/react"
}

.babelrc

ルート直下に.babelrcを作成して、以下を記述します。

.babelrc
{
  "presets": [
    [
      "next/babel",
      {
        "preset-react": {
          "runtime": "automatic",
          "importSource": "@emotion/react"
        }
      }
    ]
  ],
  "plugins": ["@emotion/babel-plugin"]
}

動作確認

cssプロパティが使用できて、デバッグ(npm run dev)したときと、ビルド(npm run buildnpm start)したときにスタイルが反映されていればOKです。

コードはCRAの場合と重複するので割愛します。

補足:nth-child を使う場合

nth-childを使う場合、さらに追加で設定が必要になるようです。
ここでは取り上げませんが、設定方法を知りたい方は、以下の記事を参考にしてください。

5
1
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
5
1