コンテンツにスキップ

04 リンター設定

このドキュメントでは、コードの品質向上とバグの早期発見のためのリンター(構文・品質チェックツール)の設定を行います。

1. リンターの概要

1.1 リンターとは

リンターは、ソースコードを静的に解析し、構文エラー、潜在的なバグ、コードスタイルの問題を検出するツールです。主な効果:

  • バグの早期発見: 実行前にエラーを検出
  • コード品質の向上: ベストプラクティスの強制
  • セキュリティの向上: 脆弱性のあるパターンの検出
  • 保守性の向上: 読みやすく理解しやすいコードの促進

1.2 使用するリンター

リンター 対象言語/ファイル 用途
ESLint JavaScript, TypeScript 構文・品質チェック
markdownlint Markdown 文書の構文・スタイルチェック
stylelint CSS, SCSS スタイルシートの品質チェック

2. ESLint の設定

2.1 ESLint とは

ESLint は JavaScript/TypeScript のための静的解析ツールで、コードの品質とスタイルの一貫性を保ちます。

2.2 パッケージのインストール

プロジェクトルートで以下のコマンドを実行します:

# ESLint 本体をインストール
npm install --save-dev eslint

# TypeScript サポート
npm install --save-dev @typescript-eslint/eslint-plugin @typescript-eslint/parser

# 推奨設定とプラグイン
npm install --save-dev eslint-config-prettier
npm install --save-dev eslint-plugin-import
npm install --save-dev eslint-plugin-node
npm install --save-dev eslint-plugin-promise
npm install --save-dev eslint-plugin-security

2.3 設定ファイル(.eslintrc.json)の作成

プロジェクトルートに .eslintrc.json ファイルを作成します:

{
    "root": true,
    "env": {
        "node": true,
        "es2022": true,
        "browser": true,
        "jest": true
    },
    "extends": [
        "eslint:recommended",
        "@typescript-eslint/recommended",
        "plugin:import/errors",
        "plugin:import/warnings",
        "plugin:import/typescript",
        "plugin:node/recommended",
        "plugin:promise/recommended",
        "plugin:security/recommended",
        "prettier"
    ],
    "parser": "@typescript-eslint/parser",
    "parserOptions": {
        "ecmaVersion": "latest",
        "sourceType": "module",
        "project": "./tsconfig.json"
    },
    "plugins": ["@typescript-eslint", "import", "node", "promise", "security"],
    "rules": {
        // エラーレベルの設定
        "no-console": "warn",
        "no-debugger": "error",
        "no-unused-vars": "off",
        "@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],

        // インポート関連
        "import/order": [
            "error",
            {
                "groups": ["builtin", "external", "internal", "parent", "sibling", "index"],
                "newlines-between": "always"
            }
        ],
        "import/newline-after-import": "error",
        "import/no-duplicates": "error",

        // TypeScript 固有
        "@typescript-eslint/explicit-function-return-type": "off",
        "@typescript-eslint/explicit-module-boundary-types": "off",
        "@typescript-eslint/no-explicit-any": "warn",
        "@typescript-eslint/prefer-const": "error",
        "@typescript-eslint/no-unused-expressions": "error",

        // Node.js 関連
        "node/no-missing-import": "off",
        "node/no-unsupported-features/es-syntax": "off",
        "node/no-unpublished-import": "off",

        // セキュリティ関連
        "security/detect-object-injection": "warn",
        "security/detect-non-literal-fs-filename": "warn",

        // Promise 関連
        "promise/always-return": "error",
        "promise/catch-or-return": "error",
        "promise/no-nesting": "warn"
    },
    "overrides": [
        {
            "files": ["*.js"],
            "rules": {
                "@typescript-eslint/no-var-requires": "off"
            }
        },
        {
            "files": ["*.test.{js,ts}", "**/__tests__/**/*"],
            "rules": {
                "security/detect-object-injection": "off",
                "node/no-unpublished-import": "off"
            }
        }
    ],
    "ignorePatterns": ["dist/", "build/", "node_modules/", "coverage/", "*.min.js"]
}

2.4 無視ファイル(.eslintignore)の作成

リンターを実行したくないファイルを指定するため、.eslintignore ファイルを作成します:

# 依存関係
node_modules/

# ビルド結果
dist/
build/
.next/
.nuxt/

# カバレッジレポート
coverage/
.nyc_output/

# 設定ファイル
*.config.js
*.config.ts

# 自動生成ファイル
*.d.ts

# ドキュメント
docs/

# ログファイル
*.log
logs/

# 一時ファイル
.tmp/
.cache/

2.5 VS Code での ESLint 設定

2.5.1 拡張機能の確認

ESLint の VS Code 拡張機能がインストールされていることを確認:

  • 拡張機能名: ESLint
  • Extension ID: dbaeumer.vscode-eslint

2.5.2 VS Code 設定の追加

.vscode/settings.json に以下の設定を追加:

{
    // ESLint の自動修正
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },

    // ESLint の検証対象
    "eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],

    // ESLint の動作設定
    "eslint.run": "onType",
    "eslint.format.enable": false,

    // 問題の表示設定
    "problems.decorations.enabled": true
}

2.6 package.json スクリプトの追加

package.json にリント用のスクリプトを追加します:

{
    "scripts": {
        "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
        "lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
        "lint:js": "eslint \"**/*.{js,jsx}\"",
        "lint:ts": "eslint \"**/*.{ts,tsx}\"",
        "lint:quiet": "eslint . --ext .js,.jsx,.ts,.tsx --quiet"
    }
}

3. markdownlint の設定

3.1 markdownlint とは

markdownlint は Markdown ファイルのスタイルと構文をチェックするリンターです。

3.2 パッケージのインストール

# markdownlint をインストール
npm install --save-dev markdownlint-cli

3.3 設定ファイル(.markdownlint.json)の作成

プロジェクトルートに .markdownlint.json ファイルを作成します:

{
    "default": true,
    "MD003": { "style": "atx" },
    "MD007": { "indent": 2 },
    "MD010": { "spaces_per_tab": 2 },
    "MD013": { "line_length": 150 },
    "MD024": { "allow_different_nesting": true },
    "MD033": { "allowed_elements": ["br", "kbd", "sub", "sup"] },
    "MD034": false,
    "MD041": false
}

3.4 VS Code での markdownlint 設定

3.4.1 拡張機能の確認

markdownlint の VS Code 拡張機能がインストールされていることを確認:

  • 拡張機能名: markdownlint
  • Extension ID: davidanson.vscode-markdownlint

3.4.2 VS Code 設定の追加

.vscode/settings.json に以下の設定を追加:

{
    // Markdown の自動修正
    "editor.codeActionsOnSave": {
        "source.fixAll.markdownlint": true
    },

    // Markdown ファイルの設定
    "[markdown]": {
        "editor.defaultFormatter": "yzhang.markdown-all-in-one",
        "editor.wordWrap": "on",
        "editor.quickSuggestions": {
            "comments": "off",
            "strings": "off",
            "other": "off"
        }
    }
}

3.5 package.json スクリプトの追加

{
    "scripts": {
        "lint:md": "markdownlint \"**/*.md\"",
        "lint:md:fix": "markdownlint \"**/*.md\" --fix"
    }
}

4. stylelint の設定(CSS プロジェクトの場合)

4.1 パッケージのインストール

CSS/SCSS を使用する場合:

# stylelint をインストール
npm install --save-dev stylelint stylelint-config-standard
npm install --save-dev stylelint-config-prettier

4.2 設定ファイル(.stylelintrc.json)の作成

{
    "extends": ["stylelint-config-standard", "stylelint-config-prettier"],
    "rules": {
        "indentation": 2,
        "string-quotes": "single",
        "color-hex-case": "lower",
        "color-hex-length": "short",
        "selector-combinator-space-after": "always",
        "selector-attribute-brackets-space-inside": "never",
        "selector-attribute-operator-space-after": "never",
        "selector-attribute-operator-space-before": "never",
        "selector-attribute-quotes": "always",
        "declaration-colon-space-after": "always",
        "declaration-colon-space-before": "never",
        "function-url-quotes": "always",
        "media-feature-colon-space-after": "always",
        "media-feature-colon-space-before": "never"
    },
    "ignoreFiles": ["node_modules/**/*", "dist/**/*", "build/**/*"]
}

4.3 package.json スクリプトの追加

{
    "scripts": {
        "lint:css": "stylelint \"**/*.{css,scss}\"",
        "lint:css:fix": "stylelint \"**/*.{css,scss}\" --fix"
    }
}

5. 統合 lint スクリプト

5.1 全体のリンタースクリプト

package.json に統合スクリプトを追加:

{
    "scripts": {
        "lint:all": "npm run lint && npm run lint:md && npm run lint:css",
        "lint:fix:all": "npm run lint:fix && npm run lint:md:fix && npm run lint:css:fix",
        "prelint": "echo '🔍 Running linters...'",
        "postlint": "echo '✅ Linting completed!'"
    }
}

6. リンターの動作確認

6.1 ESLint の動作確認

  1. テストファイルの作成

    // test-eslint.js
    var unused_var = 123;
    console.log('Hello World');
    
    function test() {
        let a = 1;
        let b = 2;
        return a + b;
    }
    
    const obj = { a: 1, b: 2 };
    
  2. リンターの実行

    npx eslint test-eslint.js
    
  3. 期待されるエラー

    • unused_var が未使用
    • セミコロンが不足
    • スペースの問題など

6.2 markdownlint の動作確認

  1. テストファイルの作成

    # Test Document
    
    This is a test.
    
    ##Bad heading
    
    - item 1
    - item 2
    
  2. リンターの実行

    npx markdownlint test.md
    

6.3 VS Code での確認

  1. 問題パネルの確認

    • Ctrl+Shift+M で問題パネルを開く
    • リンターのエラーと警告が表示されることを確認
  2. 自動修正の確認

    • ファイルを保存して自動修正が動作することを確認

7. CI/CD との統合

7.1 GitHub Actions の例

# .github/workflows/lint.yml
name: Lint Check
on: [push, pull_request]

jobs:
    lint:
        runs-on: ubuntu-latest
        steps:
            - uses: actions/checkout@v3
            - uses: actions/setup-node@v3
              with:
                  node-version: '18'
            - run: npm install
            - run: npm run lint:all

7.2 pre-commit hooks の設定

Husky を使用した例:

{
    "husky": {
        "hooks": {
            "pre-commit": "npm run lint:fix:all"
        }
    }
}

8. トラブルシューティング

よくある問題と解決方法

ESLint が動作しない

  1. 設定ファイルの確認

    • .eslintrc.json の JSON 構文をチェック
    • パーサーとプラグインの互換性を確認
  2. 依存関係の確認

    • 必要なパッケージがインストールされているか確認
  3. VS Code の設定確認

    • ESLint 拡張機能が有効化されているか確認

パフォーマンスの問題

  1. 対象ファイルの絞り込み

    • .eslintignore で不要なファイルを除外
  2. ルールの調整

    • 重いルールを無効化または警告レベルに変更

設定の競合

  1. Prettier との統合

    • eslint-config-prettier で競合するルールを無効化
  2. エディタ設定の優先順位

    • VS Code の設定とリンター設定の整合性を確認

次のステップ

リンターの設定が完了したら、次はプロジェクト固有の設定について学習します:

05_プロジェクト固有の設定.md