Next.js x TypeScript x ESLint x Prettier プロジェクトのセットアップ手順

18 min to read

Next.js x TypeScript に Linter, Formatter を導入した初期プロジェクト構築手順

どうも, こうすけ ((@kosuke_upd)) です.

今回は, Next.js x TypeScript x SCSS プロジェクトに ESLint x Prettier x stylelint x EditorConfig を導入した環境の構築手順を解説します. また, VS Code を使用したとき, ファイル保存時に自動フォーマットがかかる設定も記載しています.

汎用性が高くなるよう, 極力一般的な設定方法を採用していますので, Next.js x TypeScript プロジェクトを構築する際はぜひ参考にしてみてください.

手順

手順1. Next.js プロジェクトを作成

下記コマンドを実行し, Next.js プロジェクトを作成しましょう.

npx create-next-app <project-name>

※ ここでは <project-name>next-ts-app とします.

手順2. デフォルトのファイル構成を確認

デフォルトのファイル構成は下記の通りです.

.
├── .next # build 後のファイルが配置される
├── node_modules
├── pages # Page コンポーネント
│   ├── api
│   │   └── hello.js
│   ├── _app.js # 全ページ共通 Page コンポーネント
│   └── index.js
├── public # 画像やテキストファイルなどの静的リソース
│   ├── favicon.ico
│   └── vercel.svg
├── styles
│   ├── Home.module.css
│   └── globals.css
├── .gitignore
├── package.json
├── README.md
└── yarn.lock

今回 pages/api は使わないので削除します.

手順3. TypeScript 化に必要なパッケージをインストール

下記コマンドを実行し, Next.js の TypeScript 化に必要なパッケージをインストールしましょう.

yarn add -D typescript @types/react @types/react-dom @types/node

手順4. .js ファイルを .tsx に変更

拡張子が .js のファイル拡張子を .tsx に変更しましょう.

今回だと, pages/_app.js , pages/index.js が対象になります.

手順5. TypeScript の設定ファイルと型ファイルを追加

下記コマンドを実行し, 開発用サーバーを起動しましょう.

yarn dev

すると下記2ファイルが自動生成されます. これらは, TypeScript の設定ファイルと型ファイルです.

tsconfig.json
next-env.d.ts

また, 今回は厳し目のルールにするために, tsconfig.json 内の "compilerOptions": { "strict": false }"compilerOptions": { "strict": true } に変更しておきます.

その後, Ctrl + C にて開発用サーバーを一旦停止しておきます.

手順6. コンポーネントファイルに型を追加

.tsx に変更したコンポーネントファイルに型を追加し, コンポーネントもアロー関数に変更しましょう.

// pages/_app.tsx

import { FC } from 'react'
import { AppProps } from 'next/app'
import '../styles/globals.css'

const MyApp: FC<AppProps> = ({ Component, pageProps }: AppProps) => {
  return <Component {...pageProps} />
}

export default MyApp
// pages/index.tsx

import { NextPage } from 'next'
import Head from 'next/head'
import styles from '../styles/Home.module.css'

const Home: NextPage = () => {
  return (
    <div className={styles.container}>
      // ...
    </div>
  )
}

export default Home

手順7. Sass のインストール

今回 SCSS を使いたいので, 下記コマンドを実行し, Sass をインストールしましょう.

yarn add -D sass

手順8. .css ファイルを .scss に変更

拡張子が .css のファイル拡張子を .scss に変更しましょう.

今回だと, styles/globals.css , styles/Home.module.css が対象になります.

また, 呼び出し元も下記のように変更しておきましょう.

import '../styles/globals.css'import '../styles/globals.scss'

import styles from '../styles/Home.module.css'import styles from '../styles/Home.module.scss'

手順9. ESLint 系のパッケージをインストール

下記コマンドを実行し, ESLint 系パッケージをインストールしましょう.

yarn add -D eslint eslint-plugin-react eslint-plugin-react-hooks eslint-plugin-jsx-a11y @typescript-eslint/eslint-plugin @typescript-eslint/parser

手順10. ESLint の設定ファイルを作成

ルート直下に .eslintrc.js ファイルを作成し, 内容を下記のように記述しましょう.

module.exports = {
  ignorePatterns: ['!.eslintrc.js', '!.prettierrc.js'],
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/eslint-recommended',
  ],
  plugins: ['@typescript-eslint', 'react'],
  parser: '@typescript-eslint/parser',
  env: {
    browser: true,
    node: true,
    es6: true,
    jest: true,
  },
  parserOptions: {
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
  rules: {
    'react/prop-types': 'off',
    'react/react-in-jsx-scope': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
  },
}

手順11. Prettier 系のパッケージをインストール

下記コマンドを実行し, Prettier 系のパッケージをインストールしましょう.

yarn add --dev prettier eslint-plugin-prettier eslint-config-prettier

手順12. Prettier の設定ファイルを作成

ルート直下に .prettierrc.js ファイルを作成し, 内容を下記のように記述しましょう.

module.exports = {
  semi: false,
  singleQuote: true,
}

さらに, 先程作成した .eslintrc.js ファイルの中に下記を追加しましょう.

module.exports = {
  // ...
  extends: [
    // ...
    'plugin:prettier/recommended',
    'prettier/@typescript-eslint',
  ],
  // ...
}

最終的な .eslintrc.js の内容は下記のようになっているはずなので確認しましょう.

module.exports = {
  ignorePatterns: ['!.eslintrc.js', '!.prettierrc.js'],
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:prettier/recommended',
    'prettier/@typescript-eslint',
  ],
  plugins: ['@typescript-eslint', 'react'],
  parser: '@typescript-eslint/parser',
  env: {
    browser: true,
    node: true,
    es6: true,
    jest: true,
  },
  parserOptions: {
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
    },
  },
  settings: {
    react: {
      version: 'detect',
    },
  },
  rules: {
    'react/prop-types': 'off',
    'react/react-in-jsx-scope': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
  },
}

手順13. stylelint 系のパッケージをインストール

スタイルにも Lint, Format がかかるよう stylelint を導入しましょう.

下記コマンドを実行し, stylelint 系のパッケージをインストールします.

yarn add -D stylelint stylelint-config-recommended-scss stylelint-order stylelint-scss

手順14. stylelint の設定ファイルを作成

ルート直下に .stylelintrc.js ファイルを作成し, 内容は下記のようにします.

module.exports = {
  extends: 'stylelint-config-recommended-scss',
  plugins: ['stylelint-order', 'stylelint-scss'],
  rules: {
    'order/properties-alphabetical-order': true,
    'scss/at-rule-no-unknown': null,
    'scss/at-import-no-partial-leading-underscore': null,
  },
}

手順15. EditorConfig の設定ファイルを作成

コーディングスタイルをより一貫したものにするために EditorConfig も導入しましょう.

ルート直下に .editorconfig ファイルを作成し, 内容を下記のようにします.

root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

手順16. 必要な VS Code 拡張機能をインストール

これまで導入した Linter, Formatter をエディタで有効化するために, VS Code 拡張機能をインストールしましょう.

今回の設定だと, Prettier は ESLint から呼び出すため, Prettier の VS Code 拡張機能のインストールは不要です.

手順17. VS Code の設定ファイルを作成

プロジェクトのルート直下に .vscode フォルダを作成し, その中に settings.json を作成しましょう. そして下記の設定を記述します.

// .vscode/settings.json

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

上記設定を追加することで, ファイル保存時に今回設定したルールに従って自動フォーマットしてくれます.

また, プロジェクト内に VS Code の設定ファイルを置くことで, 個別の VS Code の設定ファイルをプロジェクト内の VS Code 設定ファイルが上書きしてくれ, メンバー間でも設定ファイルを共有できます.

手順18. npm script を追加

手順17でファイル保存時にフォーマットがかかるようにしましたが, npm script を追加して Lint, Format できるようにするとなお良いでしょう.

package.json に下記記述を追加しましょう.

{
  // ...
  "scripts": {
    // ...
    "lint": "eslint --ext .js,.jsx,.ts,.tsx --ignore-path .gitignore .",
    "stylelint": "stylelint \"**/*.scss\""
  },
  // ...
}

あとは, 下記コマンドを実行することで Lint と Format をかけることができます.

yarn lint # ESLint の Lint
yarn lint --fix # ESLint の Format

yarn stylelint # stylelint の Lint
yarn stylelint --fix # stylelint の Format

最後に

以上で Next.js x TypeScript x SCSS プロジェクトのセットアップと Linter, Formatter の導入は完了です.

yarn dev を実行して開発用サーバーを起動し, http://localhost:3000 にアクセスして開発を進めていきましょう.

参考資料

\ 記事が良かったらシェア! /

むらかこうすけ

むらかこうすけ

フリーのソフトウェアエンジニア.

Web アプリ, スマホアプリの開発が得意で, 今はゲームに関するプロダクトを仲間とともに開発しています.

ゲーム, 旅行がめちゃくちゃ好きです.

当ブログは Gatsby を用いて構築した完全自作ブログです.

UPDATE