TypeScript + node.js + VisualStudioCodeの開発環境

node.jsでアプリケーションをつくるのに、TypeScriptで書いて、Visual Studio Codeを開発環境とする方法を探る

参考になったサイト

https://qiita.com/notakaos/items/3bbd2293e2ff286d9f49
https://qiita.com/kurogelee/items/cf7954f6c23294600ef2
https://github.com/TypeStrong/ts-node/issues/46#issuecomment-437758378

ここのボイラープレートをテンプレートにすると便利です。必要なnpmパッケージ、設定ファイルがはいっています。git cloneなどでローカルに。
https://github.com/notakaos/typescript-node-base

package.json

{
  "name": "typescript-node-base",
  "keywords": [],

  "version": "0.1.0",
  "main": "dist/index.js",
  "scripts": {
    "dev": "ts-node ./src/index.ts",
    "dev:watch": "ts-node-dev --respawn src/index.ts",
    "clean": "rimraf dist/*",
    "tsc": "tsc",
    "build": "npm-run-all clean tsc",
    "start": "node ."
  },
  "keywords": [],
  "author": "YOUR NAME",
  "license": "ISC",
  "description": "",
  "dependencies": {},
  "devDependencies": {
    "@types/node": "^12.7.4",
    "npm-run-all": "^4.1.5",
    "rimraf": "^2.7.1",
    "ts-node": "^8.3.0",
    "ts-node-dev": "^1.0.0-pre.42",
    "typescript": "^3.6.2"
  }
}

L9: --respawnを指定することで、サーバ型ではないスクリプトでも、実行後終了せずに待機させ、更新→再読み込み→再起動が可能に。

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2019",
    "module": "commonjs",
    "sourceMap": true,
    "outDir": "./dist",
    "strict": true,
    "noImplicitAny": true,
    "esModuleInterop": true
  },
  "include": ["src/**/*"]
}

sourceMapは有効にしましょう。Debugが効くようになります。

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "ts-node[debug]",
      "type": "node",
      "request": "launch",
      "args": ["${workspaceFolder}/src/index.ts"],
      "runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}",
      "restart": true,
      "protocol": "inspector"
    }
  ]
}

L8: 任意のファイルを指定

https://github.com/TypeStrong/ts-node/issues/46#issuecomment-437758378
の投稿が参考になりました。