BLOG

ブログ

React.js/Next.js + TypeScript + ChakraUIの環境構築

フロントエンドエンジニアのハコザキです。
今回は、React.js/Next.js + TypeScript + ChakraUIの環境構築方法についてご紹介します!

はじめに

本記事ではNext.jsのバージョンが13のものをインストールしてますが、
ベータ機能は使わずこれまで通りの構成のまま環境構築を進めております。
(2022年11月現在)

各バージョンは以下の通りで進めていきます。

Node v16.15.1
Yarn v1.22.19

Next.jsプロジェクトの環境構築

$ npx create-next-app --ts
Need to install the following packages:
  create-next-app
Ok to proceed? (y) y
✔ What is your project named? … next-chakra-sample

プロジェクト名は next-chakra-sample にしました

以下のようにエラーなくインストールされていればokです。

Installing dependencies:
- react
- react-dom
- next

yarn add v1.22.19
info No lockfile found.
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...

success Saved lockfile.
success Saved 17 new dependencies.
info Direct dependencies
├─ next@13.0.3
├─ react-dom@18.2.0
└─ react@18.2.0
info All dependencies
├─ @next/env@13.0.3
├─ @next/swc-darwin-arm64@13.0.3
├─ @swc/helpers@0.4.11
├─ caniuse-lite@1.0.30001431
├─ client-only@0.0.1
├─ js-tokens@4.0.0
├─ nanoid@3.3.4
├─ next@13.0.3
├─ picocolors@1.0.0
├─ postcss@8.4.14
├─ react-dom@18.2.0
├─ react@18.2.0
├─ scheduler@0.23.0
├─ source-map-js@1.0.2
├─ styled-jsx@5.1.0
├─ tslib@2.4.1
└─ use-sync-external-store@1.2.0
✨  Done in 50.70s.

Installing devDependencies:
- eslint
- eslint-config-next
- typescript
- @types/react
- @types/node
- @types/react-dom

Next.jsはv13.0.3、React.jsはv18.2.0がインストールされます。

yarn devで起動し、 localhost:3000で表示できればokです

$ cd next-chakra-sample/
$ yarn dev
初期表示

pages, styles を src へ移動

初期構成

プロジェクトの初期構成は上記のようになっています。
tsconfig.jsonやpackage.jsonなどの設定ファイル以外を一つのフォルダにまとめたいため、
srcフォルダを作成し、pages/ styles/を移動します。

$ mkdir src && mv {pages,styles} src/

パスエイリアスの設定

コンポーネントのimportは相対パスではなく、絶対パスで読み込みたいです

# △
import Hoge ../../***/***.tsx
# ○
import Hoge @/***/***.tsx

tsconfig.jsonにbaseUrlなどを追記します。

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    // 追記
    "baseUrl": "./",
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"]
}

動作確認のため、以下のコンポーネントを作成します

import React from "react"

const AppPageTitle: React.FC = () => <h1>たいとる</h1>

export default AppPageTitle

続いて、 src/pages/index.tsx を編集します。

import AppPageTitle from "@/components/common/AppPageTitle" // 追加
import type { NextPage } from 'next'
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'

const Home: NextPage = () => {
  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
				{/* 書き換え */}
        <AppPageTitle /> 

        <p className={styles.description}>
          Get started by editing{' '}
          <code className={styles.code}>pages/index.tsx</code>
        </p>

        ...

localhost:3000にアクセスし、以下のようにタイトル部分が書き換わっていれば
正常にパスのエイリアスが効いています!

たいとる になっていればok

ESLintやPrettierなどのリンターやフォーマッターにつきましては、
こちらの記事で丁寧にまとめられていたため省略します!

参考までに、ESLintなどの設定は以下のようにしてます。
ここはプロジェクトなどで適宜変更する必要があります。

{
  "extends": [
    "next/core-web-vitals",
    "plugin:import/recommended",
    "plugin:import/warnings",
    "prettier"
  ],
  "rules": {
    "import/order": [
      "error",
      {
        "alphabetize": {
          "order": "asc"
        }
      }
    ],
    "import/no-anonymous-default-export": "off"
  }
}
{
  "trailingComma": "all",
  "tabWidth": 2,
  "semi": false,
  "singleQuote": true,
  "jsxSingleQuote": true,
  "printWidth": 100
}
{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}

ここまででNext.jsの環境構築は完了です。

ChakraUIの導入

UIコンポーネントライブラリの一つでもあるChakraUIを導入します。
ChakraUIの概要はこちらの記事で丁寧にまとめられていました!

ChakraUIの公式サイトにもNext.jsへのインストール方法が記載されています。
まずは以下のコマンドでプロジェクトにインストールします。

yarn add @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^6

src/pages/_app.tsx を編集します。
アプリケーションのルートをChakraProviderで囲います。
合わせて、src/styles/globals.css を削除しておきます

import { ChakraProvider } from '@chakra-ui/react' // 追記
import type { AppProps } from 'next/app'

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <ChakraProvider>
      <Component {...pageProps} />
    </ChakraProvider>
  )
}

export default MyApp

これでChakraUIが使えるようになりました。
続いて色などを共通で管理する方法についてご紹介します!

Themeの作成

src/theme.ts を作成し、以下の記述を行います。
プロジェクトのカラーパターンやコンポーネントのサイズに対して設定することができます。

export default {
  // カラーパターン
  colors: {
    theme: {
      main: '#6AA43B',
      sub: '#456D3E',
      background: '#FFFBF5',
    },
    text: {
      headline: '#494C4F',
      body: '#000000',
      white: '#ffffff',
    },
  },
  // Option: <Radio size="lg" /> のボタンの大きさやラベルなどのサイズを上書き
  components: {
    Radio: {
      sizes: {
        lg: {
          control: {
            w: '1.875rem',
            h: '1.875rem',
          },
          label: { fontSize: '1.5rem', fontWeight: '700' },
          icon: { fontSize: '1rem' },
        },
      },
    },
  },
}

上記設定を適用するため、app.tsxを編集します。

import { ChakraProvider, extendTheme } from '@chakra-ui/react'
import type { AppProps } from 'next/app'
import customTheme from '@/theme'

const theme = extendTheme(customTheme)

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <ChakraProvider resetCSS theme={theme}>
      <Component {...pageProps} />
    </ChakraProvider>
  )
}

export default MyApp

続いて、themeで設定した値が適用できるか試してみます。
src/pages/index.tsx を編集します。

import { Box } from '@chakra-ui/react'
import type { NextPage } from 'next'

import AppPageTitle from '@/components/common/AppPageTitle'

const Home: NextPage = () => {
  return (
    <Box minH='100vh' backgroundColor='theme.main'>
      <AppPageTitle />
    </Box>
  )
}

export default Home

backgroundColor='theme.main'
こちらで theme.ts の colors.theme.mainの #6AA43B を指定しています。

文字色も同様に指定することができます。

import { Heading } from '@chakra-ui/react'
import React from 'react'

const AppPageTitle: React.FC = () => (
  <Heading as='h1' color='text.headline'>
    たいとる
  </Heading>
)

export default AppPageTitle

表示はこのようになり、
themeで指定した色がそれぞれ適用されています!

Themeの動作確認

さいごに

今回はNext.js + ChakraUIの環境構築、基本的な設定についてご紹介しました。
各設定などもう少し知りたい方は、Next.jsの公式ドキュメント
ChakraUIの公式ドキュメントで深堀りしていくと良いと思います!

  • この記事を書いた人
  • 最新の記事