Failed to hit breakpoint in TypeScript file while working with Visual Studio 2019 and Webpack

We are working on an ASP.NET MVC 5 application where we are incorporating TypeScript for client-side code and using webpack to bundle everything into a single js file. TypeScript has been installed via npm. However, we have encountered an issue where setting breakpoints in Visual Studio 2019 within a TypeScript file does not get hit. Interestingly, if we set a breakpoint using the browser's developer tools in the TypeScript file, it does show up in Visual Studio when hit. When we remove webpack from the equation and let Visual Studio compile the TypeScript file directly, we are able to set breakpoints without any issues.

Below is our packages.json file:

{
  "name": "TypeScriptWebpackPlayground",
  "version": "1.0.0",
  "description": "",
  "repository": "",
  "main": "index.js",
  "scripts": {
    "Install": "npm install",
    "WebpackDevelopment": "webpack --mode=development",
    "WebpackProduction": "webpack --mode=production",
    "Debug": "run-s Install WebpackDevelopment",
    "Release": "run-s Install WebpackProduction"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^3.0.0",
    "npm-run-all": "^4.1.5",
    "ts-loader": "^8.0.14",
    "typescript": "^4.1.3",
    "webpack": "^5.17.0",
    "webpack-cli": "^4.4.0"
  }

Here is the tsconfig:

{
  "compilerOptions": {
    "target": "es5", 
    "module": "commonjs", 
    "sourceMap": true, 
    "strict": true, 
    "esModuleInterop": true, 
    "skipLibCheck": true, 
    "forceConsistentCasingInFileNames": true 
  }
}

Here is the webpack config: (we have tried both source-map and inline-source-map)

const path = require("path");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");

module.exports = {
    entry: "./ClientApp/app.ts",
    devtool: "source-map",
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: "ts-loader",
                exclude: /node_modules/
            }
        ]
    },
    resolve: {
        extensions: [".tsx", ".ts", ".js"]
    },
    output: {
        path: path.resolve(__dirname, "Scripts/custom"),
        filename: "bundle.js"
    },
    plugins: [
        new CleanWebpackPlugin()
    ]
};

This is the one-line TypeScript file where we are trying to set a breakpoint:

alert("Please break here!");

Answer №1

After struggling with the same issue for a few days, I couldn't find any solutions that worked for me. However, I stumbled upon a workaround that may also help you. First, ensure that your webpack.config.js includes the following lines:

const webpack = require('webpack');

// ...

devtool: "inline-source-map",
    plugins: [
        new webpack.SourceMapDevToolPlugin({})
    ]

// ...

With these configurations, your compiled JavaScript bundle should now have a .map file to aid in debugging.

The real magic happens when you follow these steps:

  1. Set a breakpoint on the desired line in your TypeScript file using Visual Studio.
  2. Run the application as usual.
  3. Open the Inspector tool (F12 or right-click -> Inspector).
  4. In the Sources tab, look for a cloud icon labeled webpack:// and navigate to your TypeScript files. Add a breakpoint on the same line where you placed it in Visual Studio.
  5. Reload the page or continue to the section of code where the breakpoint should trigger.
  6. Visual Studio will halt at the specified point, but you may need to reapply the breakpoint once more for it to work correctly.

I hope this tip proves helpful to you or anyone else encountering similar issues.

Answer №2

It seems like an issue that has been persistent for a while, one that Microsoft has been advocating for quite some time: https://developercommunity.visualstudio.com/t/the-breakpoint-will-not-be-hit-breakpoint-set-but/675860

Even in Visual Studio 2019 version 16.10.4, the problem still persisted.

After extensive research and trying out various recommended solutions, a member of our team decided to delve into the logs generated by Visual Studio in this specific directory/file:

Navigate to: %TEMP%

?:\Users???\AppData\Local\Tempvisualstudio-js-debugger.txt

One particular line caught their eye:

[20:12:00.532 UTC] From client: launch({"name":"Attach to Chrome program from Visual Studio","type":"chrome","request":"launch","breakOnLoad":true,"breakOnLoadStrategy":"instrument","_clientOverlayPausedMessage":"Paused in Visual Studio","logFilePath":"C:\Users\silvairls\AppData\Local\Temp\visualstudio-js-debugger.txt","trace":"info","sourceMaps":true,"showAsyncStacks":true,"smartStep":false,"url":"https://localhost:5011/","runtimeExecutable":"C:\Program Files\Google\Chrome\Application\chrome.exe","userDataDir":"C:\Users\silvairls\AppData\Local\Microsoft\VisualStudio\16.0_b9b7c470\WebTools\10B84E65_BA6A8FD4","webRoot":"C:\Users\silvairls\source\repos\XXXXXXX\FrontEnds\xxx.XXXXXXX.XXX\wwwroot","port":52556})

It became apparent that Visual Studio requires the "wwwroot" directory to be present at the root level of the project, alongside the .csproj file.

In one particular project where debugging TypeScript wasn't functioning correctly, it was discovered that the required directory was missing.

Upon creating the directory, breakpoints in .ts files started working as expected. Removing the directory caused issues with debugging once again, thus revealing a pattern.

While there may be various other scenarios causing similar problems, in our case, this was the key factor.

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

Why is it that the Jasmine test is unsuccessful even though the 'expected' and 'toBe' strings appear to be identical?

I have been developing a web application using Angular (version 2.4.0) and TypeScript. The application utilizes a custom currency pipe, which leverages Angular's built-in CurrencyPipe to format currency strings for both the 'en-CA' and &apos ...

A guide on how to retrieve images from a URL and save them using Blob in Angular 5

In my web application, I have a few links that lead to files with different content types - some are application/pdf and others are image/jpeg. When clicking on these links, the file should download or save based on their respective type. While downloadin ...

Can the inclusion of additional parameters compromise the type safety in TypeScript?

For demonstration purposes, let's consider this example: (playground) type F0 = (x?: string) => void type F1 = () => void type F2 = (x: number) => void const f0: F0 = (x) => console.log(x, typeof(x)) const f1: F1 = f0 const f2: F2 = f1 f ...

How to transfer the label text value from html to .ts file in Ionic 3?

Hey everyone! I just started using Ionic and I'm wondering how to pass the value of a label text from HTML to the .ts file. Here's a snippet of my code: <div class="box" (click)="openChatBot()"></div> <ion-label>LEADER ...

Is it possible to have an optional final element in an array?

Is there a more graceful way to declare a Typescript array type where the last element is optional? const example = (arr: [string, string, any | undefined]) => console.log(arr) example(['foo', 'bar']) When I call the example(...) f ...

Exploring the Concept of Dependency Injection in Angular 2

Below is a code snippet showcasing Angular 2/Typescript integration: @Component({ ... : ... providers: [MyService] }) export class MyComponent{ constructor(private _myService : MyService){ } someFunction(){ this._mySer ...

Using Required and Partial with an Array of Generic Types

I'm currently working with the following types: interface Color { color: string } type DarkerColor<T> = T & Color & { darker: string } type ColorInfo<T> = DarkerColor<T> & { hue: number luminance: number opacity ...

uncovering the secrets of tree shaking when using an npm package in conjunction with webpack

Imagine having an npm package where all components are exported from a single index.js file: export * from './components/A'; export * from './components/B'; Now consider another package that relies on this initial package: import {A} ...

Using a functional wrapper component to reset the modal field in Reactstrap upon closing and reopening

In the main component that displays a list of to-do tasks, we have the ability to add or edit existing tasks. To facilitate this functionality, a separate wrapper was created. import React, { useEffect, useState } from 'react'; import { Label ...

Include the ActionLink options for "Details," "Edit," and "Delete" in an AJAX list using MVC 5

I am looking to incorporate ActionLink options for "Details", "Edit", and "Delete" based on the ID using an Ajax list. I have successfully displayed my list with a datatable without needing to include my columns in the script, as shown in the code snippet ...

What could be the reason behind tsx excluding attribute names with "-" in them from being checked?

Why doesn't TypeScript check attributes with a hyphen in the name? declare namespace JSX { interface ElementAttributesProperty { props:any; // specify the property name to use } } class A{ props!:{p1:string} } const tsx = <A p1="&q ...

Inheritance from WebElement in WebdriverIO: A Beginner's Guide

I am seeking a solution to extend the functionality of the WebElement object returned by webdriverio, without resorting to monkey-patching and with TypeScript type support for autocompletion. Is it possible to achieve this in any way? class CustomCheckb ...

Access exclusive content by subscribing now!

How can I return a reference to a subject from a service without allowing the receiver to call .next() on the subject? Let's say there is a service with a subject that triggers new events. class ExampleService { private exampleSubject = new Subjec ...

No TypeScript error in Angular app when assigning a string to a number data type

Today, I encountered some confusion when my app started acting strangely. It turns out that I mistakenly assigned a string to a number without receiving any error alerts. Any thoughts on why this happened? id:number; Later on: this.id = ActiveRoute.params ...

Creating a new JavaScript object using a Constructor function in Typescript/Angular

Struggling with instantiating an object from an external javascript library in Angular/Typescript development. The constructor function in the javascript library is... var amf = { some declarations etc } amf.Client = function(destination, endpoint, time ...

Switching from a Promise to an Observable using React-Redux and TypeScript

I am struggling to grasp the concept of storing a Promise response into Redux. I believe finding a solution to this issue would greatly benefit me. Currently, I am utilizing a library that returns a Promise, and I wish to save this response - whether it i ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

Challenges with Angular observables

Struggling to make observables work has been quite the challenge for me lately. My code now resembles a chaotic battleground rather than the organized structure it once was. The dreaded "ERROR TypeError: Cannot read property 'map' of undefined" ...

Tips for preventing the overwriting of a JSON object in a React application

I'm trying to compare two JSON objects and identify the differing values in the second JSON object based on a specific key. My goal is to store these mismatched values in a new JSON object. The current issue I'm facing is that when there are mult ...

Anticipated the object to be a type of ScalarObservable, yet it turned out to be an

When working on my Angular project, I utilized Observables in a specific manner: getItem(id): Observable<Object> { return this.myApi.myMethod(...); // returns an Observable } Later, during unit testing, I successfully tested it like so: it(&apos ...