LoginSignup
11

More than 5 years have passed since last update.

VS codeでES6のコードをデバッグする

Posted at

VisualStudioCode(VS code)を使ってES6で書いたファイルをデバッグしようとしたところ、思ったより難しくて若干はまりました。ネット上に古い情報が多かったのと、日本語の情報がなさそうだったのでやり方をメモしておきます。

コード

ディレクトリ構造

以下のようにsrcにコードがまとまっていて、main.jsをデバッグしたいということにして話を進めます。

├── package.json
├── .babelrc
└── src
    ├── add.js
    └── main.js

いろいろ設定

まず、VS codeの左の虫のアイコン→歯車のアイコンとクリックして、.vscode/launch.jsonを生成し、以下のように書きます。コンパイル時にsource-mapsを使うことと、コンパイル前後のファイルのパスを明示します。

vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "プログラムの起動",
      "program": "${workspaceRoot}/src/main.js",
      "sourceMaps": true,
      "outFiles": ["${workspaceRoot}/.compiled/main.js"]
    }
  ]
}

コンパイルのためのコマンドをpackage.jsonに書いておきます(この辺はそれぞれ適当にやってください)。--source-mapsオプションをつけることが重要です。

package.json
{
  ...
  "scripts": {
    "compile": "rm -rf .compiled && babel src --out-dir .compiled --source-maps"
  },
  ...
}

これで、コマンドラインで

npm run compile

してからsrc/main.jsに適当にbreak pointを設定して、虫アイコン→緑の三角アイコンとクリックすると、ちゃんと動いていることがわかると思います。

コンパイルの自動化

デバッグのためにいちいちnpm run compileと打つのが若干めんどくさいです。これを改善するため、緑の三角アイコンをクリックした際に自動的にコンパイルをしてくれるようにしましょう。

まずは.vscode/launch.jsonに一行追加します。

.vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "プログラムの起動",
      "program": "${workspaceRoot}/src/main.js",
      "sourceMaps": true,
      "outFiles": ["${workspaceRoot}/.compiled/main.js"],
+     "preLaunchTask": "compile"
    }
  ]

さらに、.vscode/tasks.jsonというファイルを追加します。

tasks.json
{
  "version": "0.1.0",
  "command": "npm",
  "isShellCommand": true,
  "args": ["run"],
  "showOutput": "silent",
  "tasks": [
    {
      "taskName": "compile",
      "isBuildCommand": false,
      "isTestCommand": false,
      "showOutput": "silent",
      "args": []
    }
  ]
}

これで、緑の三角アイコンを押すだけでコンパイルも含めてやってくれるようになります。

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11