TypeScript tsconfig.json 構成

tsconfig.json は TypeScript プロジェクトの設定ファイルであり、コンパイルオプションとプロジェクト設定を指定するために使用します。


基本構成

最も基本的な tsconfig.json ファイル。

例

{
    "compilerOptions": {
        "target": "ES2020",
        "module": "commonjs",
        "strict": true,
        "outDir": "./dist"
    },
    "include": ["src/**/*"],
    "exclude": ["node_modules", "dist"]
}

構成の説明:

  • target:コンパイル対象の JavaScript バージョン
  • module:使用するモジュールシステム
  • strict:すべての厳格な型チェックを有効化
  • outDir:出力ディレクトリ

コンパイル対象バージョン

target を使用してコンパイル先の JavaScript バージョンを指定します。

例

// tsconfig.json
{
    "compilerOptions": {
        // ES3, ES5, ES6/ES2015, ES2020, ESNext
        "target": "ES2020"
    }
}

ターゲットごとの出力の違い:

// target: ES5 - 使用 var
var greeting = "Hello";

// target: ES2020 - 使用 let/const
let greeting = "Hello";

モジュールシステム

モジュール化の方式を構成します。

例

{
    "compilerOptions": {
        "module": "commonjs",
        // 選択可能: none, commonjs, amd, umd, es6, es2020, esnext
    }
}

厳格モード

strict オプションはすべての厳格な型チェックを有効にします。

例

{
    "compilerOptions": {
        "strict": true,
        // 以下のすべてのオプションを有効にすることと同じです:
        // "strictNullChecks": true,
        // "noImplicitAny": true,
        // "strictFunctionTypes": true,
        // など
    }
}

推奨:常に strict: true を有効にすることがベストプラクティスです。


パスエイリアス

パスエイリアスを構成してインポートを簡素化します。

例

{
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "@/*": ["src/*"],
            "@components/*": ["src/components/*"]
        }
    }
}

使用方法:

import Button from "@components/Button";
import { Header } from "@/components";

ファイルの包含と除外

どのファイルをコンパイルに含めるかを制御します。

例

{
    "include": ["src/**/*"],
    "exclude": [
        "node_modules",
        "dist",
        "**/*.test.ts",
        "**/*.spec.ts"
    ]
}

よく使うコンパイルオプション一覧

オプション 説明
target コンパイル対象バージョン
module モジュールシステム
strict 厳格モード
outDir 出力ディレクトリ
rootDir ソースのルートディレクトリ
esModuleInterop ES モジュールの相互運用を許可
skipLibCheck ライブラリのチェックをスキップ
declaration .d.ts 宣言ファイルを生成

まとめ

  • tsconfig.json:TypeScript プロジェクトの設定ファイル
  • compilerOptions:コンパイルオプションの核心的な構成
  • include/exclude:ファイルの範囲を制御
  • パスエイリアス:インポートパスを簡素化
  • strict: true:常に厳格モードを有効化
その他の拡張