コンテンツへスキップ

ESLintプラグイン

Next.jsは、ベース設定にすでにバンドルされているESLintプラグイン、eslint-plugin-nextを提供しており、Next.jsアプリケーションにおける一般的な問題や課題を捕捉することができます。

リファレンス

以下のESLintプラグインからの推奨ルールセットはすべてeslint-config-next内で使用されています

これはnext.config.jsからの設定よりも優先されます。

ルール

ルールの一覧は以下の通りです

推奨設定で有効ルール説明
@next/next/google-font-displayGoogle Fontsでのfont-displayの挙動を強制します。
@next/next/google-font-preconnectGoogle Fontsでpreconnectを使用することを保証します。
@next/next/inline-script-idインラインコンテンツを持つnext/scriptコンポーネントにid属性を強制します。
@next/next/next-script-for-gaGoogle Analyticsのインラインスクリプトを使用する際にnext/scriptコンポーネントを推奨します。
@next/next/no-assign-module-variablemodule変数への代入を禁止します。
@next/next/no-async-client-componentクライアントコンポーネントが非同期関数であることを禁止します。
@next/next/no-before-interactive-script-outside-documentnext/scriptbeforeInteractive戦略をpages/_document.jsの外で使用することを禁止します。
@next/next/no-css-tags手動のスタイルシートタグを禁止します。
@next/next/no-document-import-in-pagenext/documentpages/_document.jsの外でインポートすることを禁止します。
@next/next/no-duplicate-headpages/_document.jsでの<Head>の重複使用を禁止します。
@next/next/no-head-element<head>要素の使用を禁止します。
@next/next/no-head-import-in-documentpages/_document.jsでのnext/headの使用を禁止します。
@next/next/no-html-link-for-pages内部のNext.jsページへのナビゲーションに<a>要素を使用することを禁止します。
@next/next/no-img-elementLCPの遅延と帯域幅の増加を招くため、<img>要素の使用を禁止します。
@next/next/no-page-custom-fontページ固有のカスタムフォントを禁止します。
@next/next/no-script-component-in-headnext/headコンポーネント内でのnext/scriptの使用を禁止します。
@next/next/no-styled-jsx-in-documentpages/_document.jsでのstyled-jsxの使用を禁止します。
@next/next/no-sync-scripts同期スクリプトを禁止します。
@next/next/no-title-in-document-headnext/documentHeadコンポーネントと一緒に<title>を使用することを禁止します。
@next/next/no-typosNext.jsのデータフェッチ関数における一般的なタイプミスを防止します。
@next/next/no-unwanted-polyfillioPolyfill.ioからの重複したpolyfillを禁止します。

開発中にコードエディタで直接警告やエラーを表示するために、適切な統合の使用をお勧めします。

カスタムディレクトリとファイルのLinting

デフォルトでは、Next.jsはpages/app/components/lib/、およびsrc/ディレクトリ内のすべてのファイルに対してESLintを実行します。ただし、本番ビルドの場合、next.config.jseslint設定でdirsオプションを使用して、どのディレクトリを使用するかを指定できます。

next.config.js
module.exports = {
  eslint: {
    dirs: ['pages', 'utils'], // Only run ESLint on the 'pages' and 'utils' directories during production builds (next build)
  },
}

同様に、next lintでは--dirおよび--fileフラグを使用して特定のディレクトリやファイルをlintできます。

ターミナル
next lint --dir pages --dir utils --file bar.js

モノレポ内のルートディレクトリを指定する

Next.jsがルートディレクトリにインストールされていないプロジェクト(モノレポなど)でeslint-plugin-nextを使用している場合、.eslintrcsettingsプロパティを使用して、eslint-plugin-nextにNext.jsアプリケーションの場所を伝えることができます。

eslint.config.mjs
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
})

const eslintConfig = [
  ...compat.config({
    extends: ['next'],
    settings: {
      next: {
        rootDir: 'packages/my-app/',
      },
    },
  }),
]

export default eslintConfig

rootDirはパス(相対または絶対)、グロブ(例: "packages/*/")、またはパスおよび/またはグロブの配列にすることができます。

キャッシュの無効化

パフォーマンスを向上させるため、ESLintによって処理されたファイルの情報はデフォルトでキャッシュされます。これは.next/cache、または定義されたビルドディレクトリに保存されます。単一のソースファイルの内容以上のものに依存するESLintルールを含んでおり、キャッシュを無効にする必要がある場合は、next lint--no-cacheフラグを使用してください。

ターミナル
next lint --no-cache

ルールの無効化

サポートされているプラグイン(reactreact-hooksnext)によって提供されるルールを変更または無効にしたい場合は、.eslintrcrulesプロパティを使用して直接変更できます。

eslint.config.mjs
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
})

const eslintConfig = [
  ...compat.config({
    extends: ['next'],
    rules: {
      'react/no-unescaped-entities': 'off',
      '@next/next/no-page-custom-font': 'off',
    },
  }),
]

export default eslintConfig

Core Web Vitalsとの連携

next lintが初めて実行され、**strict**オプションが選択された場合、next/core-web-vitalsルールセットが有効になります。

eslint.config.mjs
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
})

const eslintConfig = [
  ...compat.config({
    extends: ['next/core-web-vitals'],
  }),
]

export default eslintConfig

next/core-web-vitalsは、Core Web Vitalsに影響を与える場合、デフォルトでは警告である多数のルールをエラーにするようにeslint-plugin-nextを更新します。

Create Next Appで構築された新しいアプリケーションには、next/core-web-vitalsエントリポイントが自動的に含まれます。

TypeScriptとの連携

Next.js ESLintルールに加えて、create-next-app --typescriptは、next/typescriptとともにTypeScript固有のlintルールをあなたの設定に追加します。

eslint.config.mjs
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
})

const eslintConfig = [
  ...compat.config({
    extends: ['next/core-web-vitals', 'next/typescript'],
  }),
]

export default eslintConfig

これらのルールはplugin:@typescript-eslint/recommendedに基づいています。詳細については、typescript-eslint > 設定を参照してください。

Prettierとの連携

ESLintにはコードフォーマットルールも含まれており、既存のPrettier設定と競合する場合があります。ESLintとPrettierを連携させるために、ESLint設定にeslint-config-prettierを含めることをお勧めします。

まず、依存関係をインストールします。

ターミナル
npm install --save-dev eslint-config-prettier
 
yarn add --dev eslint-config-prettier
 
pnpm add --save-dev eslint-config-prettier
 
bun add --dev eslint-config-prettier

次に、既存のESLint設定にprettierを追加します。

eslint.config.mjs
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
})

const eslintConfig = [
  ...compat.config({
    extends: ['next', 'prettier'],
  }),
]

export default eslintConfig

ステージングされたファイルでLintを実行する

ステージングされたGitファイルでリンターを実行するためにlint-stagednext lintを使用したい場合は、--fileフラグの使用を指定するために、プロジェクトのルートにある.lintstagedrc.jsファイルに以下を追加する必要があります。

.lintstagedrc.js
const path = require('path')
 
const buildEslintCommand = (filenames) =>
  `next lint --fix --file ${filenames
    .map((f) => path.relative(process.cwd(), f))
    .join(' --file ')}`
 
module.exports = {
  '*.{js,jsx,ts,tsx}': [buildEslintCommand],
}

本番ビルド中のLintingの無効化

next build中にESLintを実行したくない場合は、next.config.jseslint.ignoreDuringBuildsオプションをtrueに設定できます。

next.config.ts
import type { NextConfig } from 'next'
 
const nextConfig: NextConfig = {
  eslint: {
    // Warning: This allows production builds to successfully complete even if
    // your project has ESLint errors.
    ignoreDuringBuilds: true,
  },
}
 
export default nextConfig

既存の設定の移行

アプリケーションにすでにESLintが設定されている場合は、いくつかの条件が満たされない限り、eslint-config-nextを含めるのではなく、このプラグインから直接拡張することをお勧めします。

以下の条件が真の場合

  • 以下のプラグインのいずれかがすでにインストールされている場合(個別に、またはairbnbreact-appなどの別の設定を介して)
    • react
    • react-hooks
    • jsx-a11y
    • import
  • Next.js内でBabelが設定されている方法とは異なる特定のparserOptionsを定義している場合(これは、Babel設定をカスタマイズしていない限り推奨されません)
  • インポートを処理するためにNode.jsおよび/またはTypeScriptのリゾルバーが定義されたeslint-plugin-importをインストールしている場合

これらのプロパティがeslint-config-next内でどのように設定されているかを好む場合は、これらの設定を削除するか、代わりにNext.js ESLintプラグインから直接拡張することをお勧めします。

module.exports = {
  extends: [
    //...
    'plugin:@next/next/recommended',
  ],
}

このプラグインは、next lintを実行することなく、プロジェクトに通常通りインストールできます。

ターミナル
npm install --save-dev @next/eslint-plugin-next
 
yarn add --dev @next/eslint-plugin-next
 
pnpm add --save-dev @next/eslint-plugin-next
 
bun add --dev @next/eslint-plugin-next

これにより、複数の設定で同じプラグインやパーサーをインポートすることによって発生する衝突やエラーのリスクがなくなります。

追加の設定

すでに別のESLint設定を使用しており、eslint-config-nextを含めたい場合は、他の設定の後に最後に拡張されるようにしてください。例:

eslint.config.mjs
import js from '@eslint/js'
import { FlatCompat } from '@eslint/eslintrc'

const compat = new FlatCompat({
  // import.meta.dirname is available after Node.js v20.11.0
  baseDirectory: import.meta.dirname,
  recommendedConfig: js.configs.recommended,
})

const eslintConfig = [
  ...compat.config({
    extends: ['eslint:recommended', 'next'],
  }),
]

export default eslintConfig

next設定は、parserpluginssettingsプロパティのデフォルト値の設定をすでに処理しています。ユースケースで異なる設定が必要な場合を除き、これらのプロパティを手動で再宣言する必要はありません。

他の共有可能な設定を含める場合、**これらのプロパティが上書きされたり変更されたりしないように確認する必要があります**。そうでない場合は、next設定と動作を共有する設定を削除するか、前述のようにNext.js ESLintプラグインから直接拡張することをお勧めします。