79

Debug & Run Angular2 Typescript with Visual Studio Code?

I am trying to debug Angular2 typescript application with VS code https://angular.io/guide/quickstart

Can anyone please share steps to debug & run from VS code?

Cedric Druck
  • 1,032
  • 7
  • 20
Sanket
  • 19,295
  • 10
  • 71
  • 82

10 Answers10

125

After lot of research, I found these steps-

Before you begin, make sure you have latest version of VS code. You can verify latest version – Help > Check For Updates or About.

  1. Install extension called 'Debugger for Chrome'. Once install complete, restart VS code.

  2. Go to Debug window, open launch.json using Chrome.

  3. In Launch.json configuration section, use below config

    {
        "name": "Launch localhost with sourcemaps",
        "type": "chrome",
        "request": "launch",
        "url": "http://localhost:3000/Welcome",
        "sourceMaps": true,
        "webRoot": "${workspaceRoot}"
    }
    
  4. In tsconfig.json, make sure you have "sourceMap": true

This completes your debug environment settings. Now, before you start debugging, make sure all your existing Chrome.exe instances are closed. Verify from Task Manager OR Use DOS command ‘killall chrome’

  1. Run your project, using npm start command and Chrome as default browser.

  2. Once application is run successfully, you will receive port number. Copy URL from chrome browser and paste into url section above. (NOTE: If you are using routing in your application then url would like above otherwise it will be ending index.html etc)

  3. Now, place breakpoints wherever you want in your typescript files.

  4. Again, go to debug window in VS code, and hit Run. Your tab/instance connected to debugger will looks like below.

Chrome Debugging

Matt Bierner
  • 58,117
  • 21
  • 175
  • 206
Sanket
  • 19,295
  • 10
  • 71
  • 82
  • 4
    can't understand.. 1. which extention to install. 2. where is Launch.json? – azulay7 Aug 25 '16 at 12:31
  • 3
    @azulay7 Are you using VScode for first time? Its VScode not Visual Studio 2015 IDE. Anyways, On left side, you will see **Debug** option (or use CTRL+SHFT+D) click to open Debug window. Once you open Debug window, on top right side of Debug window you will see option for **open Launch.json**. For chrome extension, you will see **Extension** option (or use CTRL+SHFT+X) on left side. Once you open Extensions windows, search for **Debugger for Chrome** Install this extension. You will have to restart VScode. Hope this helps. – Sanket Aug 25 '16 at 14:35
  • 4
    I was also struggling with "open launch.json". The steps are as follows: click on "Debug" icon in the left sidebar, then click on the cogwheel at the top right corner of the Debug window and choose "Chrome" from the drop-down list if it appears. – Ivan Krivyakov Sep 30 '16 at 16:16
  • 6
    Anyone else getting `Failed to load resource: net::ERR_CONNECTION_REFUSED (http://localhost:3000/)` – benscabbia Oct 03 '16 at 20:24
  • 3
    I'm also getting connection error on the debug port? `HTTP GET failed: Error: connect ECONNREFUSED 127.0.0.1:9222` Loading up on localhost fine. – Mangopop Oct 07 '16 at 15:35
  • Fixed that by making sure all the chrome instances were shut down, my issue now seems to be an angular-cli sourcemap complication – Mangopop Oct 07 '16 at 16:02
  • Could you also show your full ` tsconfig.json` as well, please? I haven't made one thus far. – Palu Macil Nov 04 '16 at 02:48
  • @PaluMacil here is my tsconfig.json `{ "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "removeComments": false, "noImplicitAny": false } }` It is same as quickstart article on angular2 site. – Sanket Nov 04 '16 at 04:05
  • I didn't understand all the steps but I opened a new question here : http://stackoverflow.com/questions/40443217/angular-2-debug-with-visual-studio-code-not-working as my problem is mostly with Linux I guess. In case it help anyone to find another question about that ... ;) – maxime1992 Nov 05 '16 at 21:14
  • I managed to have a partial improvement (I can now receive console.log in VSC but breakpoints not working. CF previous comment with stackoverflow link for more info) – maxime1992 Nov 06 '16 at 10:44
  • When you download the chrome debugger extension you can view the extensions page in vscode and will give you examples and instructions on how to set this up. – The Muffin Man Feb 08 '17 at 23:24
  • Do we really have to close all chrome instances ? If true, this is the worst debugger I've ever see... Can't we launch a separate window with parameter ? – Robouste Jun 07 '17 at 14:56
  • I think that now default port for Angular5, created with Angular-CLI, is 4200, so the url should be `http://localhost:4200` you can also see it in the console where you started the app with `ng serve`. – PhoneixS Mar 01 '18 at 16:57
15

Specify a userDataDir - this will avoid collisions with other Chrome instances you may already have running. I've noticed because of this, Chrome just stops listening on any port you specify. Below is what I use and it is great!

{
    "name": "Launch",
    "type": "chrome",
    "request": "launch",
    "url": "http://localhost:3000/#/about",
    "port": 9223,
    "sourceMaps": true,
    "diagnosticLogging": true,
    "webRoot": "${workspaceRoot}",
    "userDataDir": "${workspaceRoot}/out/chrome"
}

Thanks to @reecebradley - GitHub: Cannot connect to the target: connect ECONNREFUSED

Matt Bierner
  • 58,117
  • 21
  • 175
  • 206
HydTechie
  • 797
  • 10
  • 17
  • Still one may get issues.. I moved my code base to C:\(root) drive, debug was working fine. – HydTechie Nov 18 '16 at 13:31
  • angular 2 chrome debugging not working has weird reasons.. some times checkin all pending into source control, take a clean folder, latest, debug starts working...reason I dont know.. :( – HydTechie Jan 10 '17 at 13:29
  • I am using below launch json - consistently could run the debug mode code\0/: { "version": "0.2.0", "configurations": [ { "name": "Launch localhost with sourcemaps", "type": "chrome", "request": "launch", "url": "http://localhost:4200/", "webRoot": "${workspaceRoot}/app/files", "sourceMaps": true }, { "name": "Launch", "type": "chrome", "request": "launch", "url": "http://127.0.0.1:4200", "port": 9222, "sourceMaps": true, // "diagnosticLogging": true, "trace" : "verbose", "webRoot": "${workspaceRoot}", "userDataDir": "temp" } ] } – HydTechie Apr 26 '17 at 06:22
  • TRY launch option for live debugging instead of with source maps! – HydTechie Apr 26 '17 at 06:38
5

I was having a similar issue but my project also included webpack that caused the above solutions to fail. After traversing the Internet I found a solution in a thread on github:

https://github.com/AngularClass/angular2-webpack-starter/issues/144#issuecomment-218721972

Anyway, this is what was done.

Note:- Before you start you must check whether you have the latest version of visual studio code and also have installed the extension called 'Debugger for Chrome' within VS Code.

Firstly, in './config/webpack.dev.js'

  • use => devtool: 'source-map'
  • instead of => devtool: 'cheap-module-source-map'

Then install and use the write-file-webpack-plugin:

  • npm install --save write-file-webpack-plugin

Add the plugin to './config/webpack.dev.js' by adding:

  • const WriteFilePlugin = require('write-file-webpack-plugin');

under the Webpack Plugins at the top. Continue to add:

  • new WriteFilePlugin()

to the list of plugins after new new DefinePlugin(), i.e

plugins:[
    new DefinePlugin({....}),
    new WriteFilePlugin(),
    ....
]

This ensures that the source maps are written to disk

Finally, my launch.json is given below.

{
    "version": "0.2.0",
    "configurations": [{
        "name": "Launch Chrome against localhost, with sourcemaps",
        "type": "chrome",
        "request": "launch",
        "url": "http://localhost:3000/",
        "runtimeArgs": [
           "--user-data-dir",
           "--remote-debugging-port=9222"
        ],
        "sourceMaps": true,
        "diagnosticLogging": true,
        "webRoot": "${workspaceRoot}",
        "userDataDir": "${workspaceRoot}/.vscode/chrome"
    },
    {
        "name": "Attach to Chrome, with sourcemaps",
        "type": "chrome",
        "request": "attach",
        "url": "http://localhost:3000/",
        "port": 9222,
        "sourceMaps": true,
        "diagnosticLogging": true,
        "webRoot": "${workspaceRoot}"
    }]
}

notice the absence of '/dist/' in the webroot. with this config, source-maps are in ./dist/, but they point to ./src/. vscode prepends the absolute root to the workspace, and correctly resolves the file.

malmike21
  • 101
  • 1
  • 5
5

Here is an official visual studio code documentation on how to debug Angular in VSCode https://code.visualstudio.com/docs/nodejs/angular-tutorial#_configure-the-chrome-debugger

To debug the client side Angular code, we'll need to install the Debugger for Chrome extension. Open the Extensions view (Ctrl+Shift+X) and type 'chrome` in the search box. You'll see several extensions which reference Chrome. Press the Install button for Debugger for Chrome. The button will change to Installing then, after completing the installation, it will change to Reload. Press Reload to restart VS Code and activate the extension.

We need to initially configure the debugger. To do so, go to the Debug view (Ctrl+Shift+D) and click on gear button to create a launch.json debugger configuration file. Choose Chrome from the Select Environment dropdown. This will create a launch.json file in a new .vscode folder in your project which includes configuration to both launch the website or attach to a running instance. We need to make one change for our example: change the port from 8080 to 4200.

Teddy
  • 304
  • 5
  • 17
3

I had issues with this and while @Sankets answer helped it was this issue that solved it for me https://github.com/angular/angular-cli/issues/2453.

Specifically adding the below to launch.json

"sourceMapPathOverrides": {
    "webpack:///c:/foo/bar/angular-project/*": "${workspaceRoot}/*"
}
rubie
  • 150
  • 1
  • 9
3

For angular-seed:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug with chrome",
      "type": "chrome",
      "request": "launch",
      "url": "http://localhost:5555",
      "sourceMaps": true,
      "webRoot": "${workspaceRoot}/src/client",
      "userDataDir": "${workspaceRoot}/out/chrome",
      "sourceMapPathOverrides": {
        "app/*": "${webRoot}/app/*"
      }
    }
  ]
}
Matt Bierner
  • 58,117
  • 21
  • 175
  • 206
0

These mods to launch.json worked for me on MacOS, which enabled me to get the debugger & breakpoints working in a new instance of Chrome per debug session...

// This forces chrome to run a brand new instance, allowing existing
// chrome windows to stay open.
"userDataDir": "${workspaceRoot}/.vscode/chrome",
"webRoot": "${workspaceRoot}",
"sourceMaps": true,
"sourceMapPathOverrides": { "webpack:///./*": "${webRoot}/*" }
Matt Bierner
  • 58,117
  • 21
  • 175
  • 206
Simeon
  • 71
  • 2
  • 6
0

This one is tried and tested -

Step 1: Install chrome debugger: simply open the Command Palette (Ctrl+Shift+P) inside VS Code and type Extensions: Install Extension command. When the extension list appears, type 'chrome' to filter the list and install the Debugger for Chrome extension. You'll then create a launch-configuration file.

[More Details of Step 1]

Step 2: Create and update launch.json file: Two example launch.json configs with "request": "launch". You must specify either file or url to launch Chrome against a local file or a url. If you use a url, set webRoot to the directory that files are served from. This can be either an absolute path or a path using ${workspaceRoot} (the folder open in Code). webRoot is used to resolve urls (like "http://localhost/app.js") to a file on disk (like "/Users/me/project/app.js"), so be careful that it's set correctly. update Content of launch.json file as follows-

{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Launch localhost",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost/some_name",
            "webRoot": "${workspaceRoot}/wwwroot"
        },
        {
            "name": "Launch index.html (disable sourcemaps)",
            "type": "chrome",
            "request": "launch",
            "sourceMaps": false,
            "file": "${workspaceRoot}/index.html"
        },
    ]
}

[More Details of Step 2]

enthusiast
  • 961
  • 7
  • 10
0

I need to use CORS so I open chrome in with disabled web security. Then I do debugging of Angular application by attaching debugger to chrome.

CMD line to launch chrome with disabled web security:

cd "C:\Program Files (x86)\Google\Chrome\Application\"
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security --remote-debugging-port=9222

launch.json file for attaching debugger:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "attach",
            "name": "Attach to Chrome",
            "port": 9222,
            "webRoot": "${workspaceFolder}"
        },
    ]
}
Karthik
  • 1,447
  • 1
  • 18
  • 26
0

Sanket's answer was correct but I had some problems with that.

First, Launch.json is in the ".vscode" directory of the project, and second, port number should be the same as the default server port you use for launching your app. I use ng serve from cmd for launching my project and the default port number was 4200, so I changed the launch.json file as follows.

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:4200",
            "sourceMaps": true,
            "webRoot": "${workspaceFolder}"
        }
    ]
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Hamed Mahdizadeh
  • 936
  • 1
  • 15
  • 29