🔧

Next.js 15 + ESLint 9 + Prettier + VSCode 初期設定

に公開

毎回忘れるので記録しておく。

Next.js

https://nextjs.org/docs/app/getting-started/installation

import alias は使いたいのでそこだけデフォルトから変更して Yes に。
Turbopack も使いたいのでデフォルトの Yes のままで。

$ npx create-next-app@latest sample-app
✔ Would you like to use TypeScript? … No / Yes
✔ Which linter would you like to use? › ESLint
✔ Would you like to use Tailwind CSS? … No / Yes
✔ Would you like your code inside a `src/` directory? … No / Yes
✔ Would you like to use App Router? (recommended) … No / Yes
✔ Would you like to use Turbopack? (recommended) … No / Yes
✔ Would you like to customize the import alias (`@/*` by default)? … No / Yes
✔ What import alias would you like configured? … @/*

Prettier

https://nextjs.org/docs/app/api-reference/config/eslint#with-prettier

npm install --save-dev eslint-config-prettier prettier

eslint.config.mjs に prettier を追加。

const eslintConfig = [
  ...compat.extends(
    "next/core-web-vitals",
    "next/typescript",
    "prettier"
  ),

package.json の scripts に format コマンドを追記。

package.json
  "scripts": {
    "format": "prettier --write ."

ESLint

未だに設定がよくわからない。
strict-type-checkedstylistic-type-checked を利用。
もう少し緩めのルールでも良いかも。

$ npm install -D typescript-eslint
import { fileURLToPath } from "url";
import { dirname } from "path";
import tseslint from "typescript-eslint";
import { FlatCompat } from "@eslint/eslintrc";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const compat = new FlatCompat({
  baseDirectory: __dirname,
});

const withTs = (configs) =>
  configs.map((c) => ({
    ...c,
    files: ["**/*.ts", "**/*.tsx"],
    languageOptions: {
      ...(c.languageOptions ?? {}),
      parser: tseslint.parser,
      parserOptions: {
        project: ["./tsconfig.json"],
        tsconfigRootDir: __dirname,
      },
    },
  }));

export default [
  ...compat.extends("next/core-web-vitals", "next/typescript"),
  ...withTs(tseslint.configs.strictTypeChecked),
  ...withTs(tseslint.configs.stylisticTypeChecked),
  ...compat.extends("prettier"),
  {
    ignores: [
      "node_modules/**",
      ".next/**",
      "out/**",
      "build/**",
      "next-env.d.ts",
      "eslint.config.mjs",
    ],
  },
];

VSCode

推奨の拡張機能を設定。

.vscode/extensions.json
{
  "recommendations": [
    "dbaeumer.vscode-eslint",
    "esbenp.prettier-vscode"
  ]
}

保存時にフォーマットと、import 補完のときに import alias を優先。

.vscode/settings.json
{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  },
  "typescript.preferences.importModuleSpecifier": "non-relative",
  "typescript.preferences.importModuleSpecifierEnding": "auto"
}

Discussion