【Next.js】最新版の環境構築まとめ

目次

はじめに

タイトルのとおりですが、2023年最新でのTypeScript + Sass + eslint + prettierを使用したNext.jsの環境構築の方法をまとめます。

環境

本記事を執筆した時点の環境は以下のとおりです。

  • OS: macOS Ventura 13.0.1
  • チップ: Apple M1
  • Node.js: v18.13.0
  • npm: 8.19.3
  • yarn: 1.22.17
  • Visual Studio Code: 1.74.3

環境構築

以下に環境構築の方法を記載します。

Next.jsプロジェクトの作成

まずはNext.jsプロジェクトの作成です。

Next.jsプロジェクトを作成したいディレクトリに移動します。(ディレクトリは任意)

$ cd project

以下のコマンドを実行してNext.jsプロジェクトを作成します。

myappNext.jsのアプリ名ですので、適宜名前を変更してください。

–typescriptはNext.jsプロジェクトでTypeScriptを使用するために付けています。

$ yarn create next-app myapp --typescript

実行すると、いくつかの質問が聞かれます。(キーボードの「<」と「>」で選択してEnterキーで決定します)

? Would you like to use ESLint with this project? › No / Yes
→ Yesにしましょう。
→ Next.jsにてデフォルトで使用するESLintです。

? Would you like to use `src/` directory with this project? › No / Yes
→ Yesにしましょう。
→ srcディレクトリ配下にソースコードをまとめていきます。

? Would you like to use experimental `app/` directory with this project? › No / Yes
→ Yesにしましょう。
→ Next.js 13にて導入されたもので、appディレクトリを使用した新しいルーティングシステムです。

? What import alias would you like configured? › @/*
→ デフォルトの「@/*」に設定しましょう。
→ importする際に「@」エイリアスが使えるようになり、絶対パスでimportすることができます。

上記を回答した後にインストールが再開されます。

Terminalに以下のように表示されれば、Next.jsプロジェクトの作成は成功です。

.
.
.

Success! Created myapp at /Users/tomoki.imamura/project/myapp

✨  Done in 910.50s.

Next.jsプロジェクトの起動

早速ですが、作成したNext.jsプロジェクトを起動してみましょう。

作成したNext.jsプロジェクトに移動しましょう。

$ cd myapp

以下のコマンドで起動します。

$ yarn dev

Terminal上に「http://localhost:3000」と出てくるのでブラウザでアクセスしてみましょう。

Sassの導入

次いて、Sassを導入します。

-Dはパッケージを開発時のみ使用するためにdevDependenciesとして依存関係を指定するオプションです。

$ yarn add -D sass

src/app/global.cssglobal.scssに変更します。

src/app/page.module.csspage.module.scssに変更します。

上記をimportしている箇所も変更します。

import './globals.scss'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    .
    .
    .
  )
}
import { Inter } from '@next/font/google'
import Image from 'next/image'
import styles from './page.module.scss'

const inter = Inter({ subsets: ['latin'] })

export default function Home() {
  return (
    .
    .
    .
  )
}

ESLintの導入

次いて、ESLintを導入します。

導入すると言いましたが、Next.jsプロジェクトを作成したときにESLintをインストールしています。

そのため、ESLintに関連するライブラリをインストールします。

1個ずつインストールするのは手間なので、まとめてインストールします。

$ yarn add -D eslint-config-prettier eslint-plugin-sort-keys-fix eslint-plugin-typescript-sort-keys eslint-plugin-unused-imports

Next.jsプロジェクト配下に.eslintrc.jsonがすでに存在していると思いますので、このファイルを更新します。

{
  "extends": ["next/core-web-vitals", "prettier"],
  "plugins": ["import", "sort-keys-fix", "typescript-sort-keys", "unused-imports"],
  "rules": {
    "import/order": [
      "error",
      {
        "groups": [
          "builtin",
          "external",
          "internal",
          "parent",
          "sibling",
          "index",
          "object",
          "type"
        ],
        "newlines-between": "always",
        "alphabetize": {
          "order": "asc"
        }
      }
    ],
    "import/no-duplicates": "error",
    "unused-imports/no-unused-imports": "error",
    "sort-keys-fix/sort-keys-fix": "error",
    "typescript-sort-keys/interface": "error",
    "react/jsx-sort-props": "error",
    "@next/next/no-img-element": "off"
  }
}

簡単に解説します。

  • extends
    • お偉い人が作成したルールを適用します。
    • prettierは次章で追加するものですが事前に記載しています。
      • eslint-config-prettierを適用するようにしています。
  • plugins
    • ルールセットを追加します。
      • ここに追加するだけではルールが適用されません。
      • rulesでカスタマイズすることで適用されます。
  • rules
    • ルールをカスタマイズします。
      • import/order
        • importの順番を定義したとおりに整列する。
          • groups
            • importで並べる順番。
          • newlines-between
            • importのグループごとに改行を入れる。
          • alphabetize
            • importのグループを指定した順番に整列する。
      • unused-imports/no-unused-imports
        • 使用していない import文を削除する。
      • sort-keys-fix/sort-keys-fix
        • Object型のキーの順番を整列する。
      • typescript-sort-keys/interface
        • TypeScriptの型定義のプロパティのキーの順番を整列する。
      • react/jsx-sort-props
        • jsxのpropsの順番を整列する。
      • @next/next/no-img-element
        • next/imageではなく通常のimgタグの使用を許可しない。

Prettierの導入

次いて、Prettierを導入します。

Prettierライブラリをインストールします。

$ yarn add -D prettier

Next.jsプロジェクト配下に.prettierrc.jsonを作成します。

{
  "arrowParens": "always",
  "endOfLine": "lf",
  "jsxSingleQuote": true,
  "printWidth": 120,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "all",
  "tabWidth": 2
}

簡単に解説します。

  • arrowParens
    • 常にアロー関数の引数を()で囲みます。
  • endOfLine
    • 改行コードを指定します。
  • jsxSingleQuote
    • jsxで引用符としてシングルクォーテーションを使用します。
  • printWidth
  • コードを折り返す最大行を指定します。
  • semi
    • 行末にセミコロンを付与します。
  • singleQuote
    • 文字列で引用符としてシングルクォーテーションを使用します。
  • trailingComma
    • 末尾のカンマを付与します。
  • tabWidth
    • インデントのサイズを指定します。

Stylelintの導入

次いて、Stylelintを導入します。

Stylelintライブラリをインストールします。

こちらも複数あるのでまとめてインストールします。

$ yarn add -D stylelint stylelint-config-recess-order stylelint-config-standard stylelint-config-recommended-scss stylelint-config-prettier

Next.jsプロジェクト配下に.stylelintrc.jsonを作成します。

{
  "extends": [
    "stylelint-config-recess-order",
    "stylelint-config-recommended-scss",
    "stylelint-config-standard",
    "stylelint-config-prettier"
  ],
  "rules": {
    "selector-class-pattern": "^[a-z][a-zA-Z0-9-]+$"
  }
}

簡単に解説します。

  • extends
    • お偉い人が作成したルールを適用します。
  • rules
    • ルールをカスタマイズします。
      • selector-class-pattern
        • セレクタの名前を正規表現で指定します。
        • stylelint-config-standardがケバブケースしか許容していないため、module CSSのことを考慮してキャメルケースも許容するようにします。

package.jsonの更新

次いて、package.jsonを更新します。

Next.jsプロジェクト配下にpackage.jsonがあると思います。

このファイルのscriptにLintやformatのコマンドを設定します。

{
    .
    .
    .
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint --ignore-path .gitignore",
    "lint-fix": "next lint --ignore-path .gitignore --fix",
    "lint-style": "stylelint --ignore-path .gitignore './**/*.{css,scss}'",
    "lint-style-fix": "stylelint --ignore-path .gitignore --fix './**/*.{css,scss}'",
    "format": "prettier --write --ignore-path .gitignore './**/*.{js,jsx,ts,tsx,json,css,scss}'",
  },
  "dependencies": {
    .
    .
    .
  },
  "devDependencies": {
    .
    .
    .
  }
}

簡単に解説します。

scriptsに記載したコマンドはyarnの後に続けて実行することができます。

$ yarn lint
$ yarn lint-fix
$ yarn lint-style
$ yarn lint-style-fix
$ yarn format

.vscode/settings.jsonの追加

Next.jsプロジェクト配下に.vscode/settings.jsonがなければ作成してください。

{
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.fixAll.stylelint": true
  },
  "css.validate": false,
  "scss.validate": false
}

これで保存した際に自動でコードを成形してくれます。

しかし、yarn lint-fixyarn lint-style-fixで修正とは異なっているので、yarn lint-fixyarn lint-style-fix は別途実行したほうがよいでしょう。

まとめ

この記事では最新のNext.js + TypeScript + Sass + eslint + prettierの環境構築をまとめました。

環境構築は都度都度調べるのはめんどくさいのでこんな風にまとまっていると嬉しいですよね!

是非、いいねやコメントをお願いします。

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

コメント

コメントする

目次