Guide to generating external source maps for using the Chrome debugger in Vscode with Typescript and Gulp for web development

Seeking to utilize Gulp for the development of my straightforward Typescript project that runs in the browser. When using gulp-typescript, it seems to insert modules.export into the generated js files, leading me to explore some examples involving browserify.

Currently, I have the following gulp.js file:

var gulp = require('gulp');
var del = require('del');
var ts = require("gulp-typescript");
var tsProject = ts.createProject("tsconfig.json");
var sourcemaps = require('gulp-sourcemaps');
var browserify = require("browserify");
var source = require('vinyl-source-stream');
var tsify = require("tsify");

gulp.task('clean', function () {
   return del(['build/**/*']);
});

gulp.task("copy-html", function () {
   return gulp.src("*.html")
    .pipe(gulp.dest("build"));
});
gulp.task("copy-css", function () {
  return gulp.src("src/*.css")
    .pipe(gulp.dest("build"));
});
gulp.task("default", ["clean", "copy-html", "copy-css"], function () {
  return browserify({
    basedir: '.',
    debug: true,
    entries: ['src/main.ts'],
    cache: {},
    packageCache: {}
 })
.plugin(tsify)    
.bundle()    
.pipe(source('bundle.js'))        
.pipe(gulp.dest("build"));
});

The above script generates bundle.js with embedded soucemaps. While debugging on Chrome works fine, I am encountering issues trying to utilize the vscode Chrome debugger plugin from here, as breakpoints are disabled.

This is how my launch.json looks:

{
"version": "0.2.0",
"configurations": [
{
  "name": "Launch Chrome against localhost, with sourcemaps",
  "type": "chrome",
  "request": "launch",
  "file": "${workspaceRoot}/build/index.html",
  "sourceMaps": true

},
{
  "name": "Attach to Chrome, with sourcemaps",
  "type": "chrome",
  "request": "attach",
  "port": 9222,
  "sourceMaps": true,
  "webRoot": "${workspaceRoot}"
  }
 ]
}

I attempted to incorporate external source maps using gulp-sourcemaps from here, but encountered build errors whenever I tried adding .pipe(sourcemaps.init()) and .pipe(sourcemaps.write()) to the script.

Despite testing several suggestions, none seem to work (for instance, using outDir in launch.json results in the error Property ourDir is not allowed). Therefore, I am seeking guidance on integrating a debugger with Typescript in Chrome - a seemingly common scenario, yet proven challenging to implement successfully. My assumption is that the issue lies within the (embedded) sourcemaps, but I'm uncertain.

Your assistance in this matter would be greatly appreciated!

Answer №1

Is your "Launch Chrome" actually launching Chrome and locating your localhost? I don't see any URL option in there. I started with the example code you shared, but it didn't work for me right away. I had to add some additional options from another source to get it to work properly. Here's how my "launch" configuration looks:

    {
        "name": "Chrome : Launch with sourcemaps",
        "type": "chrome",
        "request": "launch",
       // "preLaunchTask": "sync",
        "url": "http://localhost:3000",
        "webRoot": "${workspaceRoot}",
        "sourceMaps": true,
        "runtimeArgs": [
        "--remote-debugging-port=9222"
        ]
    }

Make sure to take note of the port number for localhost, which is what my browserSync is using (and remember that browserSync should be started first, either through a preLaunchTask or manually via a gulp task). Since I'm not familiar with browserify or typescript, I can't guarantee this code will work seamlessly with them. However, I suggest trying to add the URL option with your port number and including the runtimeArgs option to see if that resolves any issues.

Answer №2

I encountered a similar issue and was able to resolve it by configuring the sourceRoot parameter in my build task. However, I opted not to use browserify...

You might want to consider incorporating gulp-sourcemaps into your pipeline:

gulp.task("default", ["clean", "copy-html", "copy-css"], function () {
  return browserify({
    basedir: '.',
    debug: true,
    entries: ['src/main.ts'],
    cache: {},
    packageCache: {}
 })
 .pipe(sourcemaps.init())
 .plugin(tsify)    
 .bundle()    
 .pipe(source('bundle.js'))
 .pipe(sourcemaps.write({includeContent: false, sourceRoot: '/src'}))        
 .pipe(gulp.dest("build"));
});

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

Uh oh! An issue occurred: Cannot access values of an undefined property (reading 'valueOf')

I am attempting to loop through the JSON data and extract the start time and end time keys. I have tried two different methods in my API code to achieve this. The console.log is not showing any errors, but the other loop method is causing an error to appea ...

Using typescript with create-react-app - organizing types in a separate file

I'm currently developing a project using Create React App with TypeScript (create-react-app myapp --typescript) In my App.tsx file, I have written some TypeScript code that I want to move to an external file. I have tried creating App.d.ts, index.d.t ...

An automatic conversion cannot handle spaces and prohibited characters in Object keys

The AlphaVantage API uses spaces and periods in the keys. Their API documentation is not formal, but you can find it in their demo URL. In my Typescript application, I have created data structures for this purpose (feel free to use them once we solve the ...

Having trouble accessing the record by clicking on a table cell

I'm attempting to dynamically click on a cell within a row by passing the text of the cell. Here is my code: await element.all(by.xpath('//div/table/tbody/tr')).then(rows => { rows.find(row => { return row.all(by.tagName(&apo ...

Tips for clicking a .class a random number of times:

Could someone help me figure out how to click a random number of times on the element with class name .CLASS when a key is pressed? I think I need to incorporate the Math.floor(Math.random()) function, but I'm not sure how to do it in my existing code ...

What are the best practices for testing a class function that executes a mongoose query?

Within my class, there are multiple class functions, with one specifically executing a mongoose query. The structure is similar to: export class ExampleService { constructor( @InjectModel(Example.name) private exampleModel: Model<Example>, ...

Using AngularJS to create a numeric input with a non-numeric model

I've encountered an error message related to an input field that is set as type "number" while the actual model is a string. The reason for this discrepancy is that my ngModel value is utilized in other areas of the application. However, for a specif ...

Looking to leverage RxJs 6 GroupBy for stream organization? Interested in consolidating emissions from various Grouped Observables?

Input Observable stream: The information is retrieved from an observable stream, which stems from a REST request for various projects. This data is obtained in the form of Observable<Project[]>. const project1: Project = { id: 1, ...

How to retrieve an array of objects using Angular 2 service?

I am facing an issue with my Angular 2 service component. It is responsible for populating an array of objects, and I need to access this array from other components in the program. However, the getUsers() method always returns null as shown in the code sn ...

Issues with troubleshooting in Visual Studio Code

Currently, I am in the process of debugging C++ code using VS Code and I need to pass an argument to start debugging. When running the program in the command line, it is as simple as: [user@localhost ~]$ ./hello-world 10 Can anyone advise on how to config ...

Troubleshooting Angular 2 Typescript: Component not displaying as expected

I am currently in the process of learning Angular 2. Despite encountering numerous error messages, I have successfully set up the routes and can now display the desired component. My next challenge is to incorporate a navbar component into my homepage comp ...

Error TS2339: The 'selectpicker' property is not found on the 'JQuery<HTMLElement>' type

Recently, I integrated the amazing bootstrap-select Successfully imported bootstrap-select into my project with the following: <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstra ...

What is the correct way to specify the type in my functional component?

I was trying to define the type in my component in a different way, I know it can be done using classes but is there a way to achieve this with functional components without exporting the interface? Despite my extensive research, I couldn't find any r ...

The call in TypeScript React does not match any overload

Encountering an error with a React component that I wrote and seeking assistance. The primary component code snippet: export interface ICode { code: (code: string) => void; } export default class UserCode extends React.Component{ state = { formFil ...

implement some level of control within the ngFor directive in Angular

For instance, let's say I have an ngfor loop: <ng-container *ngFor="let setting of settings | trackBy: trackById"> <button mat-button [matMenuTriggerFor]="menu">Menu</button> <mat-me ...

Creating a type-safe method wrapper in TypeScript based on function names

Many Q&As discuss creating a function wrapper in TypeScript, but my question is how to do the same with named methods. I am interested in writing something similar to this JavaScript code: function wrap(API, fnName, fn) { const origFn = API.p ...

Angular 2 - Changes in component properties not reflected in view

I'm currently delving into Angular 2 and as far as I know, interpolated items in the view are supposed to automatically update when their corresponding variable changes in the model. However, in the following code snippet, I'm not observing this ...

What is the best approach for submitting a form with data through a POST request in an Ionic application?

I am facing an issue while trying to make a POST request in Ionic for submitting a form with an array of data. Surprisingly, it works perfectly fine when I test it on POSTMAN. https://i.sstatic.net/t8sEG.jpg Although I attempted to use this form, it did ...

Showing or hiding elements based on user roles in Angular 4

I am currently working on a project that involves multiple user types (SuperUser - SchoolAdmin - Teacher). Each role has specific privileges to access certain elements. How can I dynamically hide elements based on the logged-in user's role using *ng ...

How can I prevent Chrome from constantly prompting for permission to access the camera?

I have been working on some HTML/JavaScript/WebRTC projects that involve using the webcam. Despite hosting the files from my local web server (127.0.0.1), Chrome always prompts me for permission to access the camera each time I reload the page. Is there a ...