🖍️

eslintでコードを自動チェックする

2025/01/10に公開

vscodeの拡張機能でチェックできるeslintをもっとカスタムしようと思います
拡張機能はこちらです
https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint

環境

windows 10
node v20.16.0
vscodeにeslint拡張機能をインストール済み

作成

next.jsのサンプルプロジェクトにeslintを適用してみます
eslintを利用するか書かれるのでYesとしてあとは任意でどちらか適当に選択します
https://nextjs-ja-translation-docs.vercel.app/docs/getting-started

> npx create-next-app@latest --typescript
Need to install the following packages:
create-next-app@15.1.0
Ok to proceed? (y) y

√ What is your project named? ... my-app
√ Would you like to use ESLint? ... No / Yes
√ 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 for `next dev`? ... No / Yes
√ Would you like to customize the import alias (`@/*` by default)? ... No / Yes
√ What import alias would you like configured? ... @/*
Creating a new Next.js app in C:\sandbox\react\my-app.

Using npm.

Initializing project with template: app-tw


Installing dependencies:
- react
- react-dom
- next

Installing devDependencies:
- typescript
- @types/node
- @types/react
- @types/react-dom
- postcss
- tailwindcss
- eslint
- eslint-config-next
- @eslint/eslintrc


added 370 packages, and audited 371 packages in 2m

140 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
Initialized a git repository.

Success! Created my-app at C:\sandbox\react\my-app

eslintはインストールされましたが、スタイルチェックはないので追加します。
https://eslint.style/packages/default#rules

> npm i -D @stylistic/eslint-plugin

added 2 packages, and audited 373 packages in 6s

141 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

eslintの設定ファイルを編集します
プロジェクト作成時にファイル(eslint.config.mjs)が作成されます
スタイルルールを定義したいので追記します

eslint.config.mjs
import { dirname } from "path";
import { fileURLToPath } from "url";
import { FlatCompat } from "@eslint/eslintrc";
+ import stylistic from '@stylistic/eslint-plugin';

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

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

const eslintConfig = [
  ...compat.extends("next/core-web-vitals", "next/typescript"),
+  {
+    plugins: {
+      '@stylistic': stylistic
+    },
+  },
+  stylistic.configs['recommended-flat']
];

export default eslintConfig;

エラーの確認

vscodeでスタイルルールエラーがでていることをみれるようにします

  1. vscodeでショートカットCtrl+shift+@を同時におしてターミナルをだします
  2. 「問題」タブに切り替えます
  3. 表示しているファイルにエラーがある場合、エラーが表示されます
    eslintエラーの確認をしている画面キャプチャ

参考

package.jsonに"type": "module"を指定しない場合、拡張子が.mjsでないと機能しないようです

# eslint.config.jsにファイル名を変えて実行

> npm run lint

> > my-app@0.1.0 lint
> > next lint

(node:9108) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
Cannot use import statement outside a module

GitHub Actionsで自動チェックさせる

指定したタイミングでeslintチェックさせるようにします
github actions についてはこちらにて
https://docs.github.com/ja/actions/about-github-actions/understanding-github-actions

.github/workflows フォルダを作成後ワークフローファイルを作成後
https://docs.github.com/ja/actions/use-cases-and-examples/building-and-testing/building-and-testing-nodejs
をもとに作成しました

lint-check.yml
name: my-app lint check
on:
  pull_request:
    branches:
      - main
    paths:
      - '**.tsx'
      - '**.ts'
      - '**.d.ts'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: checkout
        uses: actions/checkout@v4
      
      - name: get changed files
        id: changed-files
        uses: tj-actions/changed-files@v45

      - name: set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: cache node_modules
        id: cache-node_modules
        uses: actions/cache@v4
        with:
          path: ${{ github.workspace }}/node_modules
          key: ${{ runner.os }}-node_modules-${{ hashFiles('**/package-lock.json') }}

      - name: install npm package
        if: |
          ${{ steps.cache-node_modules.outputs.cache-hit != 'true' }}
          || contains(steps.changed-files.outputs.all_changed_files, 'package.json')
          || contains(steps.changed-files.outputs.all_changed_files, 'package-lock.json')
        run: npm ci

      - name: lint check
        run: npm run lint       

mainブランチに対してプルリクエスト作成かつ変更したファイルがtsx, ts, d.tsファイルだったときのみ実行されます

Discussion