GeekFactory

int128.hatenablog.com

vscodeでWSLのnode.jsをデバッグ実行する

Visual Studio Code(vscode)はnode.jsのデバッグに対応していますが、Windows Subsystem for Linux(WSL)のnode.jsも利用できるようです。

debugging Node.js in the Linux subsystem on Windows:

If you want to run Node.js in the Linux subsystem on Windows (WSL), you can use the approach from above as well. However to make this even simpler, we've introduced a useWSL flag to automatically configure everything so that Node.js runs in the Linux subsystem and source is mapped to files in your workspace.

https://code.visualstudio.com/docs/nodejs/nodejs-debugging#_remote-debugging

以下の環境で試してみました。

vscode.vscode/launch.json を作成します。

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "node (WSL)",
      "useWSL": true,
      "program": "${workspaceFolder}/index.js"
    },
    {
      "type": "node",
      "request": "launch",
      "name": "node (macOS)",
      "program": "${workspaceFolder}/index.js"
    }
  ]
}

なお、macOSなどで useWSL: true にするとエラーになってしまうため、WSL専用の構成を追加する必要があります。

WSLでnodeが実行できることを確認します。コマンドラインで以下を実行してバージョンが表示されればOKです。

wsl.exe node -v

nvmを使っている場合は .bashrcnvm.sh を読み込んでおく必要があります。私は普段zshを使っているため、bashでnvmを有効にするのを忘れていてハマりました。

vscodeデバッグnode (WSL) を選び、無事にnode.jsが起動したらOKです。