5分でNode.js+TypeScript+ESLint環境をつくる

自分への覚書です。

最低限の設定でNode.js+TypeScript+ESLintの環境を作ります。

事前にNode.jsはインストールしておきます。バージョンはインストール後に node -v で確認可能です。

プロジェクトのディレクトリを作って移動する

node-ts-20220422 というディレクトリを作成して移動します。(ディレクトリ名はなんでもOKです)

$ mkdir node-ts-20220422 && cd "$_"

プロジェクトを初期化する

$ npm init -y

必要なモジュールのインストール

npm install --save-dev eslint typescript @types/node @typescript-eslint/parser @typescript-eslint/eslint-plugin

tsconfig の設定

こちらを参考にして、使っているnodeのバージョンに合わせてtsconfig.jsonを作成します。

今回はnode V14です。

{
  "compilerOptions": {
    "lib": ["ES2020"],
    "module": "commonjs",
    "target": "ES2020"
  }
}

ESLint の設定

.eslintrc.js を作成します。

module.exports = {
  root: true,
  parser: '@typescript-eslint/parser',
  plugins: ['@typescript-eslint'],
  extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'],
}

適当なコードを書いて試す

適当なコードを書きます。

const myFunc = (num: number) => num + 1

console.log(myFunc(2))

tsc でトランスパイルします。

$ npx tsc

実行します。

$ node src/main.js
3

あえて型エラーにするために、以下のように変更します。

const myFunc = (num: number) => num + 1

console.log(myFunc('2'))

tsc でエラーになることを確認します。

$ npx tsc
src/main.ts:3:20 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.

3 console.log(myFunc('2'))
                     ~~~


Found 1 error in src/main.ts:3

eslint が効いていることを確認するため、使われていない変数を定義してわざと怒られてみます。

const myFunc = (num: number) => num + 1

console.log(myFunc('2'))

const a = 'tami'
$ npx eslint src/main.ts

/Users/tamibouz/project/node-ts-20220422/src/main.ts
  5:7  warning  'a' is assigned a value but never used  @typescript-eslint/no-unused-vars

✖ 1 problem (0 errors, 1 warning)

以上です。

参考情報

https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping

https://typescript-eslint.io/docs/linting/