2022/08/22

Next.js + TailwindCSSのプロジェクト立ち上げ時のメモ

nextjstailwind-css

Next.js + Tailwind CSSのプロジェクト作成時の備忘録です。

環境

% node -v
v18.7.0
% yarn -v
1.22.19
% npx -v
8.15.0

プロジェクトの作成・Tailwind CSSの初期化

# create app
% npx create-next-app@latest --ts your-project-name
% cd your-project-name

# add .idea to .gitignore(jetbrain社製のIDE"webstorm"を使う方用)
% cat <<EOF >> .gitignore

# ide
.idea/
EOF

# introduce tailwind
% yarn add --dev \
    tailwindcss \
    @tailwindcss/forms \
    @tailwindcss/typography \
    postcss \
    autoprefixer \
    sass \
    styled-components
% yarn add \
    @headlessui/react \
    @heroicons/react
% npx tailwindcss init -p

tailwind.config.jsを編集

/** @type {import('tailwindcss').Config} */
const colors = require('tailwindcss/colors')
// define your own theme color here
colors.primary = colors.indigo
// colors.secondary = colors.purple

module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx}',
    './components/**/*.{js,ts,jsx,tsx}',
  ],
  theme: {
    extend: {
      colors,
      fontFamily: {
        inter: ['Inter', 'sans-serif'],
      },
    },
  },
  plugins: [
    require('@tailwindcss/forms'),
    require('@tailwindcss/typography'),
  ],
}

global.cssを編集

@import url('https://rsms.me/inter/inter.css');

@tailwind base;
@tailwind components;
@tailwind utilities;

prettierを導入

% yarn add --dev \
    prettier \
    eslint-config-prettier\
    eslint-plugin-unused-imports

.eslintrc.jsonを以下のように編集

{
  "extends": ["next/core-web-vitals", "prettier"],
  "plugins": ["unused-imports"],
  "rules": {
    "@typescript-eslint/no-unused-vars": "off",
    "unused-imports/no-unused-imports": "error",
    "unused-imports/no-unused-vars": "off"
  }
}

.prettierignore ファイルを追加

cat <<'EOF' > .prettierignore
###
# Place your Prettier ignore content here

###
# .gitignore content is duplicated here due to https://github.com/prettier/prettier/issues/8506

# Created by .ignore support plugin (hsz.mobi)
### Node template
# Logs
/logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env

# parcel-bundler cache (https://parceljs.org/)
.cache

# next.js build output
.next

# nuxt.js build output
.nuxt

# Nuxt generate
dist

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless

# IDE / Editor
.idea

# Service worker
sw.*

# macOS
.DS_Store

# Vim swap files
*.swp

# static resources
public
EOF

prettierの設定ファイルを追加

cat <<'EOF' > .prettierrc
{
  "semi": false,
  "singleQuote": true,
  "tabWidth": 2,
  "useTabs": false
}
EOF

package.jsonファイルにprettierのコマンド追加

{
  "scripts": {
+   "lintfix": "prettier --write --list-different .",
  }
}
# 以下のコマンドを実行して、prettierを実行してコードの整形が可能になりました。
% yarn lintfix

husky/commitlintを導入

% yarn add --dev \
    husky \
    lint-staged \
    @commitlint/{cli,config-conventional}
% husky install

% cat <<'EOF' > .husky/commit-msg
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
. "$(dirname "$0")/common.sh"

yarn commitlint --edit $1
EOF

% cat <<'EOF' > .husky/common.sh
command_exists () {
  command -v "$1" >/dev/null 2>&1
}

# Workaround for Windows 10, Git Bash and Yarn
if command_exists winpty && test -t 1; then
  exec < /dev/tty
fi
EOF

% cat <<'EOF' > .husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
. "$(dirname "$0")/common.sh"

yarn lint-staged
EOF

% cat <<'EOF' > commitlint.config.js
module.exports = {
  extends: ['@commitlint/config-conventional'],
}
EOF

% chmod +x .husky/commit-msg
% chmod +x .husky/common.sh
% chmod +x .husky/pre-commit

package.jsonにlint-stagedを追加

  "lint-staged": {
    "**/*.{js,jsx,ts,tsx}": [
      "eslint"
    ],
    "*.**": [
      "prettier --check --ignore-unknown"
    ]
  },

Recoilと複数レイアウト対応の導入

% yarn add recoil
  • pages/_app.tsx を以下のように編集
import '../styles/globals.css'
import type { ReactElement, ReactNode } from 'react'
import type { NextPage } from 'next'
import type { AppProps } from 'next/app'
import { RecoilRoot } from 'recoil'

export type NextPageWithLayout = NextPage & {
  getLayout?: (page: ReactElement) => ReactNode
}

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout
}

function MyApp({ Component, pageProps }: AppPropsWithLayout) {
  const getLayout = Component.getLayout ?? ((page) => page)
  return <RecoilRoot>{getLayout(<Component {...pageProps} />)}</RecoilRoot>
}

export default MyApp

References