Having trouble debugging the current TypeScript file in VS Code because the corresponding JavaScript file is missing

In my current project using Visual Studio Code version 1.17, I am focusing on debugging the current typescript file. As part of my setup, I have a build task in place which generates a corresponding javascript file structure like so:

src/folder1/folder2/main.ts
src/folder1/folder2/main.js

To achieve this debugging objective, I attempted to configure the launch.json file as follows:

{
  "type": "node",
  "request": "launch",
  "name": "Current File",
  "program": "${file}",
  "console": "integratedTerminal",
  "outFiles": [
    "${workspaceFolder}/${fileDirname}**/*.js"
  ]
}

Unfortunately, running into an error message stating:

Cannot launch program '--full-path-to-project--/src/folder1/folder2/main.ts' because corresponding JavaScript cannot be found.

Despite the existing of the respective JavaScript file!

Here's a glimpse at my tsconfig.json setup:

{
"compileOnSave": true,
"compilerOptions": {
    "target": "es6",
    "lib": [
        "es2017",
        "dom"
    ],
    "module": "commonjs",
    "watch": true,
    "moduleResolution": "node",
    "sourceMap": true
    // "types": []
},
"include": [
    "src",
    "test"
],
"exclude": [
    "node_modules",
    "typings"
]}

Answer №1

It is possible that the issue lies within your map files rather than the configuration itself.

Prior to attempting any other solutions, it is crucial to verify that the paths specified in your launch configuration are accurate.

You can confirm this by temporarily substituting the paths with absolute paths on your system to test if they function correctly.

If the issue persists, consider the following steps:

Review your tsconfig file and ensure that the mapRoot within compilerOptions remains unset. According to the official documentation:

Specifies where the debugger should locate map files instead of their generated locations. Use this flag if the .map files will be situated at a different location during run-time than the .js files. The designated location will be included in the sourceMap to guide the debugger in locating the map files.

More information can be found here.

In most cases, it is advisable not to set any specific value for it.

Additionally, confirm that

"sourceMap": true`

is configured in the compilerOptions section of your tsconfig.json file and that map files are being successfully generated.

Answer №2

Your outFiles configuration is pointing to the incorrect directory.

To resolve this issue, update your launch.json configuration by replacing it with the following:

{
  "type": "node",
  "request": "launch",
  "name": "Current File",
  "program": "${file}",
  "console": "integratedTerminal",
  "outFiles": ["${fileDirname}/*.js"]
}

Referencing the Visual Studio Code launch.json variable reference:

${fileDirName} represents the current opened file's directory name

Ensure that the directory specified in outFiles matches your requirements.

You can also use

"outFiles": ["${fileDirname}/**/*.js"]
to include subdirectories if needed.

The current configuration adds the following directory:

"${workspaceFolder}/${fileDirname}**/*.js"

This results in a path similar to:

"/path/to/root/path/to/root/src/folder1/folder2/**/*.js"

Essentially, the path to the root directory is duplicated, making it invalid.

If your .js files reside in a different outDir: simply specify the correct directory path. Typescript sourceMaps will handle the rest.

For instance, if your .js files are located in a dist directory:

"outFiles": ["${workspaceFolder}/dist/**/*.js"]

Answer №3

If you happen to come across this situation: when using webpack for your project, make sure to set the devtool option to generate source maps that are compatible with VS Code. After some trial and error, I found that both 'cheap-module-source-map' and 'source-map' work effectively. Here is what I added to my webpack.config.js file:

devtool: env.production ? 'source-map' : 'cheap-module-source-map'

Answer №4

Make sure that source maps are enabled within your tsconfig.json file.

"sourceMap": true,

Answer №5

My issue was resolved by including "sourceMap": true in the tsconfig.json file.

The configuration in my launch.json now appears as follows:

{
"version": "0.2.0",
"configurations": [
  {
    "type": "node",
    "request": "launch",
    "name": "Launch Program",
    "program": "${workspaceFolder}/src/index.ts",
    "preLaunchTask": "tsc: build - tsconfig.json",
    "outFiles": ["${workspaceFolder}/build/**/*.js"]
  }
]
}

Answer №6

Don't forget that in order to successfully run a program file, it needs to have the focus before execution. Otherwise, you may encounter a 'Cannot find Javascript' error dialog, especially if the file is not a Javascript or Typescript file. This is because the default configuration in the launch.json file specifies "program": "${file}", which means the currently displayed file will be executed.

For instance, if you are working on a non-js or non-ts file like tsconfig.json or launch.json, clicking the Run command will trigger the error dialog.

Setting up a Typescript project correctly in VS Code

Prior to creating the project, ensure that Typescript and Node.js are installed on your machine.

1. Initialize in the terminal

Begin by creating a new folder for your project in the terminal.

mkdir MyProject

Change the directory to the newly created folder.

cd MyProject

Initialize the project to enable Typescript and generate the tsconfig.json file.

tsc --init

Open the folder in VS Code using the following command (macOS specific) or manually.

code .

2. Configure the output directory

In the tsconfig.json file, add the following lines under compilerOptions to specify the output directory. Remember to define this in the tsconfig.json instead of launch.json, as VS Code looks for files in the default outDir specified there (${workspaceFolder}/**/*.js).

"outDir": "./out",  /* Specify .js output files. */
"sourceMap": true   /* Generate corresponding .map files. */

Running/Debugging the project

Create a simple test program: welcome.ts

console.log('Welcome to Typescript');

1. Build

Trigger the Run Build Task (Shift + Command(Ctrl) + B) from the Terminal menu in VS Code and enter the command:

tsc: watch - tsconfig.json

This should be done once initially to start monitoring code changes.

2. Run

To run the Typescript program, make sure the program file with a .ts extension has focus. From the Run menu:

Choose Start Debugging for debugging (F5)

OR

Select Run Without Debugging (Ctrl + F5)

The output will be visible in the Debug Console.

It might seem daunting at first, but it's straightforward once you become familiar with it.

Answer №7

After following @lucascaro's suggestions, my machine was working perfectly fine. However, when testing the same setup on another computer with identical versions of vscode, node, ts, etc., I was still encountering an error message.

If you have implemented all of @lucascaro's instructions and are still seeing the error message, consider adding the following to your launch.json configuration after the program property:

{
  ...
  "preLaunchTask": "tsc: build - tsconfig.json",
  ...
}

This addition resolved the issue on the second machine, but interestingly caused it to stop working on my own. If you are facing similar challenges, give this solution a try.

Answer №8

If you're facing a similar issue, try this solution that worked for me:

To resolve the problem, navigate to your gulpfile.js and locate the line containing sourcemaps.write(). Modify this line as follows:

.pipe(sourcemaps.write('.', { includeContent: false, sourceRoot: '../lib' }))

After making this adjustment, rebuild your project and attempt debugging once more. I found this helpful tip thanks to roblourens on GitHub. You can view his original comment here. Additionally, he referenced this page, which provided valuable insights.

Answer №9

After some troubleshooting, I discovered that the issue was caused by changing the working directory in my launch.json file to a different location:

"cwd": "${workspaceFolder}/dist"

It's possible that this behavior is due to a bug in VSCode.

Answer №10

When I encountered this issue, the Base url was initially created as

"baseUrl": "./",

within the tsconfig.json file.

After modifying it to

"baseUrl": "./src"

The mapping feature began functioning correctly.

Answer №11

In my situation, I included

"sourceRoot": "../../"
within the compiler options of tsconfig.json.

Make sure to verify the relative path

"sourceRoot": ""
that is generated in app.js.map files. The entry
"sourceRoot":"../../","sources":["src/app.ts"]
clearly specifies the absolute path of your .ts files.

Answer №12

Hey there, I encountered a similar issue not too long ago. The solution is simple - just include the path to your npm installation in either the user path or the global path variable.

C:\Users\yourName\AppData\Roaming\npm 

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

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

Using regular expressions in Sublime Text 2 to replace text in JSON files can greatly improve your workflow

After using an online web tool to convert an Excel file to JSON, I now require assistance in replacing certain values within the JSON. Currently, I am using Sublime Text 2. {"Time (GMT-04:00)":"2010-07-06 08:30:00","Skin temp - average":"34,2043","Step Co ...

Having difficulty transitioning a function with a promise from JavaScript to TypeScript

I am currently in the process of transitioning my existing NodeJS JavaScript code to TypeScript for a NodeJS base, which will then be converted back to JavaScript when running on NodeJS. This approach helps me maintain clear types and utilize additional fe ...

angularjs code to dynamically change the selected index of an option in a document

This code snippet demonstrates how to achieve this functionality using pure JavaScript: document.getElementById("mySelect").selectedIndex = "0" <select class="selectpicker" id="mySelect"> <option>English &nbsp;</option> < ...

Having trouble with PHP Storm and Vue component not working? Or encountering issues with unresolved function or method in your

I have been struggling with this issue for days and cannot seem to find a solution online. Being new to Vue.js, I am currently working on a TDD Laravel project: My goal is to add the standard Vue example-component to my app.blade.php as follows: app.bla ...

Divs are not being organized into rows correctly due to issues with Bootstrap styling

I have implemented Bootstrap in my Angular application. The stylesheet link is included in my Index.html file as follows: <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css"> In addition to that, I have listed Bootstrap a ...

Exploring request parameters within an Express router

I'm currently facing an issue with accessing request parameters in my express router. In my server.js file, I have the following setup: app.use('/user/:id/profile', require('./routes/profile')); Within my ./routes/profile.js fil ...

Trouble setting custom attribute tags in Ionic 4

Trying to apply custom attributes within a ngFor loop is proving challenging for me. <ng-container *ngFor="let a of this.current_items?.areas; let i = index"> ... I've made several attempts: <div class="productBatchArea" custom-data=&apo ...

The issue of HTTP parameters not being appended to the GET request was discovered

app.module.ts getHttpParams = () => { const httpParamsInstance = new HttpParams(); console.log(this.userForm.controls) Object.keys(this.userForm.controls).forEach(key => { console.log(this.userForm.get(key).value) const v ...

Leveraging the local variables within a function in conjunction with the setTimeout method

Currently, I'm facing an issue with a website that I'm working on. I have created a function that should add a specific class to different ids in order to make images fade out one by one on the home page. To streamline the process, I used a local ...

Steps to Extract the key value from the parseJson() function

Could someone assist me in retrieving the value of the "id_user" key from the script provided below? JSON.parse({ "data": [ { "id_user": "351023", "name": "", "age": "29", "link": "http://domain. ...

Using JavaScript to dynamically write content to the document in the

What is the correct way to write the HTML break tag "<br>" in JavaScript without it causing a line break? I want the tag to be displayed as text. For example, "the break tag in html is ..." See below for an example of what I am looking for. <scr ...

What is the reason for Jquery AJAX appending additional path to the relative path?

I am encountering an issue with the following code snippet $.ajax({ url: "search/prefetch", success: function (data) { $(".result").html(data); alert("Load was performed."); }, dataType: "json" } ...

Mastering Array Dispatch in VueJS

I've encountered an issue while trying to send an array of data to the backend. I attempted to include [] in the dispatch variables and on the backend, but it only captures the last data sent to the backend. My objective is to associate each data with ...

What is causing the inefficacy of this particular SQL request method, while the alternative one proves effective?

It's surprising that the one not working is from the mssql package page. Why isn't it functioning on my machine? What am I missing here? The other example I found online works perfectly. On a side note - should these requests be done asynchronou ...

Issue with Hover Effect on Safari Browser

Encountering a peculiar issue exclusively in Safari - when hovering over a link in the header, the links to the right of the hovered-over link alter their size (appearing smaller) during the hover animation. Once the animation concludes, these links revert ...

What is the best method to delete an attribute from an element using Angular?

When working with Angular, how can I remove an attribute or its value? For example, say I have an ng-click event that I only want to fire once. One approach could be to create a 'self-destruct' in the ng-click event like this: elementClicked = f ...

Can Express POST / GET handlers accommodate the use of jQuery?

I created a simple Express server to retrieve data from an HTML form and make queries to OpenWeatherMap using that data: const { OpenWeatherAPI } = require("openweather-api-node"); const express = require("express"); const bodyParser = ...

Is there a way to verify if an element possesses a specific style, and if so, alter the style of a different element accordingly?

Could you assist me in achieving a similar effect as demonstrated below: I have two menus (http://osiyo-nur.uz/osiyo-nur.uz/test6/), one of which is initially invisible. When I hover over the first menu, the second menu becomes visible with an overlay eff ...

Using JavaScript to dynamically add items from a menu and include a delete button for the option to remove them

//I am embarking on an exciting AJAX lab where I will be experimenting with dynamic element creation and deletion. Below is a snippet of the code to get started. //Generate elements and text nodes along with a deletion button for each item in the cart fu ...

Mastering data extraction from JSON using React JS (with Axios)

Being new to ReactJS and axios, I am facing a challenge. I need to iterate through JSON data and extract values where the key is a number (e.g. 0, 1, 2...). However, I am unsure how to implement this in my code since the server provides dynamic JSON data ...