sh1’s diary

プログラミング、読んだ本、資格試験、ゲームとか私を記録するところ

TypeScript セットアップ方法のメモ

f:id:shikaku_sh:20210908174035p:plain:w400

TypeScript を使うコーディングをはじめるときに、VScode だとターミナルを使ってプロジェクトの初期設定をすると思います。

この部分は、新しくてよい書き方の更新が本当にはやいので、とりあえず最近書いたものをメモ。

うっかり TSLint を入れないようにするために書きました。

ターミナルで実行するコマンド

# package.json の準備
npm init
# typescript のインストール
npm install --save-dev typescript
# Node.js 用の型宣言
npm install --save-dev @types/node
# tsconfig.json の作成
npx tsc --init
# ESLint パッケージのインストール
npm install --save-dev eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser

2021 年現在、TypeScript のリンターとして推奨されるのは ESLint です。(2019 年に TSLint は非推奨になりました)

ESLint パッケージのインストールは3つをまとめていて、それぞれ:

  • ESLint パッケージ
  • ESLint の TypeScript 用プラグイン
  • ESLint が TypeScript を理解できるようにパースする役割のパッケージ

バージョンをチェックしてみます。

$ ./node_modules/.bin/eslint --version
v7.32.0

tsconfig.json ファイルの修正

自分の環境にあわせて設定すること。

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Projects */

    /* Language and Environment */
    "target": "es6",                                     /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "lib": ["ES6"],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */

    /* JavaScript Support */

    /* Emit */
    "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    "outDir": "./dist",                                   /* Specify an output folder for all emitted files. */

    /* Interop Constraints */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */

    /* Completeness */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  },
  "include": [
    "./src"
  ]
}

ESLint の設定ファイルを追加

手動で、TypeScript の設定ファイル(ESLint の設定ファイルを読み込むためのもの)を作成します。

touch tsconfig.eslint.json
{
    "extends": "./tsconfig.json",
    "include": [
      "src/**/*.ts",
      ".eslintrc.js"
    ],
    "exclude": [
      "node_modules",
      "dist"
    ]
  }

手動で、ESLint の設定ファイルを作成します。

touch .eslintrc.js
module.exports = {
    root: true,
    parser: '@typescript-eslint/parser',
    parserOptions: {
        sourceType: 'module',
        // cmaVersion: 2019, // Node.js 12 = 2019 (他のバージョンの Node.js を利用しているときは変更)
        tsconfigRootDir: __dirname,
        project: ['./tsconfig.eslint.json']
      },
    env: {
      es6: true,
      node: true,
    },
    plugins: [
      '@typescript-eslint',
    ],
    extends: [
      'eslint:recommended',
      'plugin:@typescript-eslint/eslint-recommended',
      'plugin:@typescript-eslint/recommended',
      'plugin:@typescript-eslint/recommended-requiring-type-checking',
    ],
    rules: {
    },
};

extends の設定はデフォルトでは無効になっている型チェックを有効化しています。型チェックを増やすほど、リントに使う時間が増えるため、トレードオフを考慮する必要があります。

ただ、初心者のうちは型チェックを覚える意味でも拡張しておくほうがよいと私は思います。

実行確認

ESLint の設定ができたら実行できるかチェックします:

npx eslint src/index.ts

src フォルダーに index.ts を追加しています。ファイルの中に何も記述していないため、「何も出力されない」結果が正常です。

すべての .ts ファイルをリンスするときはつぎのとおり:

npx eslint . --ext ts

ESLint を使うにあたってわかるのは、マニュアルにしてもなんにしても英語がある程度わからないと、勘違い(誤訳)が発生したり時間がかかることになる。
なんだかんだいっても、基礎学力は基礎学力であって欠かせないものです。

参考