Pause the execution at specific points within Typescript files by utilizing breakpoints when debugging with an attached debugger in VsCode

My current challenge involves setting up a debugger in VsCode with the attach mode on a Typescript codebase running in a Docker container. Despite successfully attaching the debugger in VsCode and hitting breakpoints, I consistently find myself landing on the compiled Javascript code rather than the Typescript code.

https://i.sstatic.net/BJCBe.png

A simple log statement within an infinite loop is illustrated in the image provided.

index.ts

console.log('Hello world');

while(true) {
  console.log('a')
}

Prior to transitioning to Docker setup, I referenced the documentation, tested the debugger locally without any issues in hitting breakpoints on Typescript files. Below is more information about the setup:

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      "name": "Launch Program",
      "port": 9229,
      "restart": true,
      "address": "localhost",
      "remoteRoot": "./",
      "localRoot": "${workspaceFolder}",
      "outFiles": ["${workspaceFolder}/dist/**/*.js"],
      "sourceMaps": true
    }
  ]
}

docker-compose.yml

version: '3.8'
services:
  nodeserver:
    command: nodemon --inspect=0.0.0.0:9229 ./dist/index.js
    build:
      context: ./
      dockerfile: ./build/Dockerfile
    ports:
      - '3000:3000'
      - '9229:9229'

Dockerfile

FROM node:15-alpine3.11 as production

WORKDIR /opt/project

COPY package.json .
RUN yarn global add typescript
RUN yarn global add nodemon
RUN yarn install

COPY src src
COPY tsconfig.json .

RUN tsc

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    "skipLibCheck": true,                     /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

I've experimented with various setups employing nodemon and regular node, but none have successfully enabled breakpoints pointing back to the Typescript files while attaching to a process. Is this achievable?

Answer №1

Upon revisiting this issue, I successfully resolved it by following these crucial steps:

  1. Ensure that the port and address establish a connection when attaching. Look for the message "Debugger connected" in your console to confirm connectivity.

If your debugger connects but breakpoints remain unbound or errors persist in the debugger terminal, consider these troubleshooting measures:

  1. Set sourceMaps to true in your launch.json and sourceMap to true in your tsconfig.json. This will generate the necessary files for hitting breakpoints on TS files and inform your debugger to utilize them.
  2. If you're working within a specific workspace in your docker environment (e.g., WORKSPACE /opt/project), ensure that your remoteRoot in your launch.json is configured accordingly. If no workspace is used, set the value to /; steer clear of using ./ as that might cause issues.
  3. Add the property resolveSourceMapLocations to your launch.json to assist the debugger in locating your .map.js files if there are difficulties in finding them. Reference this link for more information.
  4. If your project is not housed in the root folder, verify that the localRoot property directs to the directory containing your code.
  5. If all else fails, check if you're running VsCode version 16.0 or higher; at the time of writing, there's a known issue with the debugger in VsCode versions 16 and above. These settings have been proven effective in v15.8.2.

These steps were pivotal in achieving success with this task. Here is my current launch.json configuration:

{
  // Utilize IntelliSense to explore available attributes.
  // Hover over to view descriptions of existing attributes.
  // For detailed information, visit: https://go.microsoft.com/fwlink/? 
     linkid=830387
  
 "version": "0.2.0",
 "configurations": [
 {
  "type": "node",
  "request": "attach",
  "name": "Debug: App",
  "remoteRoot": "/opt/project/",
  "localRoot": "${workspaceFolder}",
  "port": 9229,
  "restart": true,
  "sourceMaps": true,
  "resolveSourceMapLocations": ["${workspaceFolder}/**", "!**/node_modules/**"]

  // Enable only for debugging purposes.
  // "trace": true
  }
 ]
}

Answer №2

When TypeScript is transpiled into JavaScript at the process level, it can sometimes cause issues with identifying the original source format when debugging remotely. This problem can be solved by utilizing the "Remote Development" extension created by Microsoft specifically for this purpose.

If you are experiencing difficulties with debugging a Node Typescript app running in Docker, you may find the solution in this thread: Debug in VS Code a Node Typescript app running in Docker

Answer №3

I encountered a similar problem when running a node server in a docker container and trying to connect a debugger. Despite trying all the suggested solutions, none of them worked.

The root cause turned out to be our use of ts-node-dev for running the server with hot reloading. It appears that this tool copies the compiled TypeScript files into a virtual space that is not accessible on disk, making it impossible to locate the file locally. As a result, Visual Studio Code breakpoints were being set on these virtual files due to identical file paths.

We ultimately resolved the issue by switching to nodemon as an alternative solution.

Answer №4

The issue I encountered was resolved by adjusting the sourceRoot to ./ in the tsconfig.json file. The sources path had been set incorrectly, lacking a designated path.

I recommend examining the generated .map.js file to verify the sources path and confirm the configuration of the sourceRoot upon generation.

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

Discover the most helpful keyboard shortcuts for Next.js 13!

If you're working with a standard Next.js 13 app that doesn't have the experimental app directory, setting up keyboard shortcuts can be done like this: import { useCallback, useEffect } from 'react'; export default function App() { c ...

Highchart in ionic 2 not displaying

https://i.sstatic.net/q2CPR.png I inserted code for a highchart on my webpage, but it's not appearing I followed instructions from this video tutorial https://www.youtube.com/watch?v=FSg8n5_uaWs Can anyone help me troubleshoot this issue? This is ...

What steps should I take to ensure that this test covers all possible scenarios?

I recently started learning React development and am currently exploring testing with Jest and React Testing Library (RTL). However, I'm facing challenges in achieving complete test coverage for the component code below: import { CustomCardActions, ...

cycle through options of radio buttons

How can I display items of radio buttons, with the values of these items coming from a backend api? <div class="input-group col-md-9 input-group-sm"> <label>gender</label> </div> <!-- TO CORRECT ...

Neglecting the inclusion of a property when verifying for empty properties

In the code snippet below, I have implemented a method to check for empty properties and return true if any property is empty. However, I am looking for a way to exclude certain properties from this check. Specifically, I do not want to include generalReal ...

Loading and unloading an Angular 6 component

One challenge I'm facing involves creating an image modal that appears when an image is clicked. Currently, I have it set up so that the child component loads upon clicking the image. However, the issue is that it can only be clicked once and then dis ...

What is the best way to implement a switch case with multiple payload types as parameters?

I am faced with the following scenario: public async handle( handler: WorkflowHandlerOption, payload: <how_to_type_it?>, ): Promise<StepResponseInterface> { switch (handler) { case WorkflowHandlerOption.JOB_APPLICATION_ACT ...

Combining TypeScript with Vue3 to implement bootstrapVue

After using BootstrapVue as any, the error was corrected but unfortunately it still doesn't work in the browser. Here is what's inside main.ts: import { createApp }from 'vue'; import App from './App.vue'; import router from & ...

Referencing other styled-components in Typescript and React code bases

I'm attempting to replicate this code snippet found on https://styled-components.com/docs/advanced using TypeScript. const Link = styled.a` display: flex; align-items: center; padding: 5px 10px; background: papayawhip; color: palevioletred; ...

The component is failing to store its value within the database

I'm encountering an problem when attempting to save an option in the database. To address this issue, I created a component in Svelte called StatePicker that is responsible for saving US States. However, when I try to save it in the database using a ...

Tips on utilizing index and eliminating React Warning: Ensure every child within a list has a distinct "key" prop

Hello, I am encountering an issue where I need to properly pass the index in this component. Can you help me figure out how to do that? Error: react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop ...

VS Code failing to detect Angular, inundated with errors despite successful compilation

Having some issues with loading my angular project in vscode. It used to work fine, but suddenly I'm getting errors throughout the project. I have all the necessary extensions and Angular installed. https://i.stack.imgur.com/qQqso.png Tried troubles ...

Displaying properties of a class in Typescript using a default getter: Simplified guide

Here is an interface and a class that I am working with: export interface ISample { propA: string; propB: string; } export class Sample { private props = {} as ISample; public get propA(): string { return this.props.propA; } public se ...

The system is unable to process the property 'items' due to a null value

When trying to access the properties of ShoppingCart, an error is encountered stating that Property item does not exist on type {}. The mistake made in the code is unclear and difficult to identify. shopping-cart.ts import { ShoppingCartItem } from &apos ...

When deploying my Angular project, I am unable to access my files

I have been facing challenges while trying to deploy my web application with the frontend being Angular. The issue I am encountering is that I cannot access my JSON file located in the assets folder. Below is the function I am using to retrieve data from ...

Generating an array of keys from duplicated values in Typescript

My data is structured in the following array format: { itemTitle: 'value example', itemType: 'value example', itemDescription: 'value example', itemFamily: 'Asset', }, { itemTitle: 'val ...

Tally the number of sub-labels associated with each main label

In my Angular 9 application, I am looking to separate an array based on the lable field. Within each separated array, I would like to determine the count based on the subLable field. This is the array I am working with: [ {"id":1,"socia ...

The exported variable 'SAlert' is utilizing the name 'AlertInterface' from an external module

Utilizing the antd alert component (ts) with styled components import styled from 'styled-components'; import Alert from 'antd/es/alert'; export const SAlert = styled(Alert)` && { margin-bottom: 24px; border-radiu ...

Implementing advanced error handling using custom error messages with enums

I'm trying to use Zod to validate a gender field with z.nativeEnum(), but for some reason my custom error messages are not being applied: gender: z.nativeEnum(Gender, { invalid_type_error: 'Le sexe doit être homme ou femme.', ...

Is there a way to make the vss sdk treeview collapse automatically?

Is there a way to have the nodes of a combo control of type TreeView.ComboTreeBehaviorName collapsed by default? I've searched through the documentation at this link and this link, but couldn't find a solution. I also examined the types in vss. ...