Debugging AngularJS in Visual Studio Code

I am encountering an issue while trying to debug my Angular application using the new Visual Studio Code. It appears that there is a compatibility problem between Angular and Visual Studio Code.

Here is the content of my launch.json file:

{
    "version": "0.1.0",
    // List of configurations. Add new configurations or edit existing ones.
    // ONLY "node" and "mono" are supported, change "type" to switch.
    "configurations": [
        {
            // Name of configuration; appears in the launch configuration drop down menu.
            "name": "Manager",
            // Type of configuration. Possible values: "node", "mono".
            "type": "node",
            // Workspace relative or absolute path to the program.
            "program": "/Volumes/Transcend/WorkArea/Manager/app/app.js",
            // Automatically stop program after launch.
            "stopOnEntry": true,
            // Command line arguments passed to the program.
            "args": [],
            // Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace.
            "cwd": ".",
            // Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH.
            "runtimeExecutable": null,
            // Optional arguments passed to the runtime executable.
            "runtimeArguments": [],
            // Environment variables passed to the program.
            "env": { },
            // Use JavaScript source maps (if they exist).
            "sourceMaps": false
        }, 
        {
            "name": "Attach",
            "type": "node",
            // TCP/IP address. Default is "localhost".
            "address": "localhost",
            // Port to attach to.
            "port": 5858,
            "sourceMaps": false
        }
    ]
}

Upon attempting to debug my Angular app, I encountered the following error:

Error:

ReferenceError: angular is not defined
    at Object.<anonymous> (/Volumes/Transcend/WorkArea/Manager/app/app.js:1:79)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain [as _onTimeout] (module.js:497:10)
    at Timer.listOnTimeout [as ontimeout] (timers.js:112:15)
MacBook-Pro:Manager user$ cd '/Volumes/Transcend/WorkArea/Manager';  'node' '--debug-brk=55539' '/Volumes/Transcend/WorkArea/Manager/app/app.js'
debugger listening on port 55539

Killed: 9

The content of app.js is as follows:

/// <reference path="../typings/angularjs/angular.d.ts"/>

var routerApp = angular.module('uiRouter', ['ui.router', 'uiRouter.dmvs']);

routerApp.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/home');

    $stateProvider

        .state('home', {
            url: '/home',
            templateUrl: 'app/dmvs/partial-d.html',
            controller:'dController'
        })

});

Answer №1

Thanks to the assistance of the @code community, I have successfully managed to debug an Angular client from my IDE! Hopefully, this solution will be beneficial to someone else...

To begin, you will need to download the "Debugger for Chrome Extension." Simply follow these steps:

F1
ext Install Extensions
debug (then select Debugger For Chrome)

Once the extension is installed, I followed Microsoft's instructions provided at:

https://marketplace.visualstudio.com/items/msjsdiag.debugger-for-chrome

I have personally only been able to make use of the "attach" method with Chrome. Below is the final version of the launch.son file that I utilize:

{
    "version": "0.2.0",
    "configurations": [
        {
            // Use this to get debug version of Chrome running:
            // /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
            "name": "Attach",
            "type": "chrome",
            "request": "attach",
            "port": 9222,
            "webRoot": "./www"
          }
      ]
}

In addition, ensure to initiate Chrome in debug mode by executing the following command (for Mac users):

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222

Kudos to the amazing editor @code!

Note: Remember to terminate ALL Chrome instances as recommended here: https://github.com/Microsoft/vscode-chrome-debug/issues/111#issuecomment-189508090

Answer №2

Dealing with a similar issue, I encountered a problem with webpack in my project, making the usual solutions ineffective. After thorough research online, I stumbled upon a resolution thread on github:

Link to Solution on Github

Here is what needed to be done.

Note:- Ensure that you have the most updated version of visual studio code and have installed the extension named 'Debugger for Chrome' within VS Code before proceeding.

Start by modifying './config/webpack.dev.js'

  • Change => devtool: 'source-map'
  • To => devtool: 'cheap-module-source-map'

Next step is to install and use the write-file-webpack-plugin:

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

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

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

under the Webpack Plugins at the top. Also, add:

  • new WriteFilePlugin()

to the list of plugins after new DefinePlugin(), like so:

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

This ensures the source maps are saved to disk

Lastly, below is my launch.json configuration.

{
    "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}"
    }]
}

Take note that '/'dist/' is not included in the webroot. With this setup, source-maps reside in ./dist/, but are linked to ./src/. vscode appends the absolute root to the workspace, ensuring correct file resolution.

Answer №3

When working with Gulp.js, we encountered the need to incorporate the following configuration:

"sourceMapPathOverrides": {
    "/source/*":"${workspaceRoot}/[specific directory for our mappings]/*"
 }

I hope this information proves useful for individuals troubleshooting an angularjs application using VS Code.

Below is a sample configuration:

{
"version": "0.2.0",
"configurations": [
    {
        "type": "chrome",
        "request": "launch",
        "name": "Launch Chrome",
        "url": "[your URL]",
        "webRoot": "${workspaceRoot}/[directory where your application is stored]",
        "sourceMaps": true,        
        "sourceMapPathOverrides": {
            "/source/*":"${workspaceRoot}/[directory of your application along with any additional required .js files]/*"
        },        
        "userDataDir": "${workspaceRoot}/.vscode/chrome",
        "runtimeArgs": [
            "--disable-session-crashed-bubble"
        ]
    }
]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlocking the secrets of obtaining post values using Body-parser in your Express Node.js application

Currently, I am utilizing Express version 4.11.1 and Body-parser version 1.11.0 in my project. However, upon running the code snippet below, I encountered the following output: I am seeking suggestions on how to retrieve the form value. Output {} serve ...

What could be causing my code to fail in properly iterating through the array of objects in React using the id as the key?

I have successfully printed the blog array in the console, which includes the object. My goal is to utilize the object components by mapping through the id as the key, but I am unable to access the map function. Interestingly, I have used a similar map s ...

obtain the selected value from the radio button

While working on the server side, I dynamically created radio buttons with the following code: RadioButton button1 = new RadioButton(); button1.ID = question.Name + "_Radio1"; button1.Text = "Yes"; RadioButton button2 = new RadioButton(); button2.ID = qu ...

The markers from KML exported from My Maps are not showing up on the Google Maps JavaScript API

I have a map on Google My Maps that I want to showcase through the Google Maps JavaScript API. This way, I can easily merge multiple maps into one and add paths/markers without needing to code it all manually. Test out the map I'm using by clicking t ...

Issue with CoffeeScript and three.js: scene not defined

I've been troubleshooting this issue for hours, but I can't seem to figure out the error... Here's the error message I'm getting: Cannot read property 'add' of undefined Below is my coffeescript code file (hopefully it&apos ...

Next JS is trying to access a JSON file that does not exist

After setting up a route "/es/servicios" and configuring it in next.config.js: module.exports = { async redirects() { return [ { source: '/', destination: '/es', ...

What steps can I take to give priority to a particular ajax call?

Every 10 seconds, two ajax based methods are executed. However, when I submit the form for processing, it waits for the previous ajax calls to complete before processing. I want to prioritize the form submission. Below is the script that I am using: func ...

Creating a Multilevel Dropdown Menu: A Step-by-Step Guide

I am curious about how to create a multilevel dropdown menu using Bootstrap 5 and vanilla JavaScript. I created an example based on the Bootstrap 5 dropdowns component documentation, but it did not display when I clicked on it. The issue seems to be relat ...

The JSON parsing functionality is not working as expected in my app.js file

app.js: const express = require("express"); const https = require("https"); const app = express(); const port = 3000; app.get("/",function(req,res){ const url ="https://maps.googleapis.com/maps/api/geocode/jsonaddress=1600+Amphitheatre+Parkway,+Mounta ...

How can I use TailwindCSS in NextJS to remove the "gap" className from a component?

Currently, I am working on button components in NextJS with Tailwindcss and I am encountering a problem with some variants. Everything works fine, except when I remove the children (button text), I notice something strange that I can't quite figure ou ...

The downloading functionality of anchor tags is not functioning properly on mobile devices

In the process of developing a mobile app using Ionic Framework, AngularJs, and Html, I encountered an issue. There is a specific page where users are supposed to click on a <div> element to download a wallpaper image. Strangely enough, this works ...

How can I create my own custom pagination and sorting features instead of relying on the default ui-bootstrap options?

Can anyone provide assistance with resolving conflicts I am experiencing while using ui-bootstrap? ...

Can a function be activated in JavaScript when location permission is declined?

Background: Following up on a previous question regarding the use of getCurrentPosition and async functions. I am currently working on The Odin Project and attempting to create a basic weather application. My goal is to include a feature that automatically ...

Returning a 404 Error stating "Invalid request to /api/users/register."

Encountering an issue with proxy connection - unable to determine the root cause despite verifying all routes. Not able to successfully register the user and store data in MongoDB. Seeking suggestions for resolution. Thank you. Attempting to send user reg ...

Tips for updating nested documents in mongoose with Node.js

Hi everyone, I'm facing some challenges with updating a nested document using mongoose. flashcardDeck.updateOne({ _id: deck._id }, { $set: { flashcards[Math.floor(i/2)].side1: newFlashcardsArr[i]}}); I'm encountering errors when trying to specif ...

What is the best approach for utilizing the map function to render JSON data within a JavaScript function in ReactJS?

Currently, I am utilizing the material-ui library to generate card-like items. The list of these items is stored in a JavaScript file as shown below: var Items = [ { name: "Tandoori Pizza", image: "Images/pizza.png", price ...

The top border of the chart should be overlaid by the Highcharts Flag Series

My goal is to create a flag series that sits atop all plotLines in my chart, overlaying the top edge of the chart. Despite manually changing various components within the Highcharts component using Chrome DevTools and setting overflow: visible, I have not ...

Retrieving information from MongoDB

Currently, I am working on retrieving data from MongoDB and passing it to my Express server to eventually display it in my HTML using Angular. The retrieval process is successful when there is only one record in the database. However, if multiple records a ...

Tips for determining what elements are being updated in terms of style

I need assistance with modifying the functionality of a webpage's dropdown menu. Currently, it displays when the mouse hovers over it, but I want to change it to appear on click using my own JavaScript. Despite setting the onmouseout and onmouseover e ...

Why aren't my properties being reflected in the state after making changes?

Here is my Component Container code: import React, { Component } from 'react'; import { connect } from 'react-redux'; import Example from '../components/example.jsx'; class ExampleContainer extends Component { render() { ...