Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VSCode Debugging #46

Closed
amcdnl opened this issue Dec 15, 2015 · 82 comments
Closed

VSCode Debugging #46

amcdnl opened this issue Dec 15, 2015 · 82 comments
Labels
external research Needs design work, investigation, or prototyping. Implementation uncertain. wontfix you can do this Good candidate for a pull request.

Comments

@amcdnl
Copy link

amcdnl commented Dec 15, 2015

VSCode will not recognize any breakpoints hit.

@blakeembrey
Copy link
Member

blakeembrey commented Dec 20, 2015

You're going to have to provide more information for me to replicate. I personally don't even use VSCode, so have no idea what this issue even means or where to start. How do I reproduce it? It's unlikely it's an issue with ts-node, but I don't know where to start.

@amcdnl
Copy link
Author

amcdnl commented Dec 21, 2015

@blakeembrey absolute; so its rather simple. do require('ts-node/register') and set a breakpoint in any file from there. I'm positive its related to source maps not getting mapped correctly when using register. If you need more details, let me know if you can't reproduce and i'll create a demo repo.

What IDE you use? VSCode seems like a obvious TS user IDE.

@enlight
Copy link

enlight commented Dec 23, 2015

I've hit this issue today, though I'm not using the latest revision and it seems like there have been some changes to source map generation lately. The main problem here I think is that VSCode seems to require access to a .js file on disk, but ts-node doesn't emit the generated code to a file. The TypeScript inlineSources compiler options could've perhaps provided a workaround, unfortunately according to the docs https://code.visualstudio.com/docs/editor/debugging

VS Code supports inlined source maps but not inlined source

so that's a dead end unless someone adds support for it in VSCode.

@blakeembrey
Copy link
Member

Yeah, it sounds like this is unlikely to ever work then. That's unfortunate. VSCode would have to hook into source-map-support to make this happen, which someone might be able to do easily enough. Since all the generated files and source maps are in memory, if there's some way to communicate that then we can make it work, otherwise you'll have to rely on actually transpiling files for now.

@jonaskello
Copy link
Contributor

I am using ts-node to run mocha. I can get debugging to work in Webstorm although there are issues:

  1. Webstorms own breakpoints does not work, I need to explicitly add a "debugger" statement in the source code.
  2. Webstorm highlights the wrong line. It is about 20 lines off from the debugger statement. But the locals, watches and stack displays correct information.

Is there some way to verify that the source maps generated in memory are correct when running mocha?

@jonaskello
Copy link
Contributor

Tried setting both inlineSourceMap and inlineSources to true in tsconfig.json but exact same behaviour in Webstorm.

@blakeembrey
Copy link
Member

The source maps are all correct, I believe the issue is what I mentioned above - the fact they don't have access to the source maps. If there's some way to make access possible, I'll investigate it. Perhaps the source map location could be absolute and I could write the files into a temporary directory during execution.

@arolson101
Copy link

Looks like things have changed- https://code.visualstudio.com/docs/editor/debugging:

VS Code supports both the inlined source maps and the inlined source.

I've tried turning on these options but breakpoints still don't work for me. My config:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Test",
            "type": "node",
            "request": "launch",
            "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
            "stopOnEntry": false,
            "args": ["--require", "ts-node/register", "test/table.test.ts"],
            "cwd": "${workspaceRoot}",
            "preLaunchTask": null,
            "runtimeExecutable": null,
            "runtimeArgs": [
                "--nolazy"
            ],
            "env": {
                "NODE_ENV": "development"
            },
            "externalConsole": false,
            "sourceMaps": true,
            "outDir": null
        },

@blakeembrey
Copy link
Member

@arolson101 I believe you misunderstand. There's no difference. TypeScript still does not have access to the source maps of ts-node - they are in memory. I have a working debugger just fine with VS Code, but you need to emit the .js and source map files for VS Code to consume (and configure outDir) and not use ts-node.

@blakeembrey
Copy link
Member

Coming back to this, I use VS Code now and often use the debugging feature. However, I recommend you compile the JavaScript files with source maps and execute those directly instead. It's pretty simple with VS Code to set up a CLI task that watches and compiles using tsc and restarts the program while listening to the debugger.

@amcdnl
Copy link
Author

amcdnl commented Jun 11, 2016

😒

@nbransby
Copy link

Does this mean no translated stack traces from node when an uncaught exception is thrown whilst debugging in vscode?

@blakeembrey
Copy link
Member

No. How are you debugging in vscode?

@nbransby
Copy link

Without using ts-node, obviously works fine but I switched to ts-node so I could have proper stack traces on a crash but then the debugger doesn't pick up the breakpoints. So I have both configs in my launch.json and I just comment in/out the relevant one depending if I want to debug or run

@blakeembrey
Copy link
Member

blakeembrey commented Jun 24, 2016

Did you read this issue?

@blakeembrey
Copy link
Member

If you want to re-map errors according to source maps, I'd recommend checking out https://github.com/evanw/node-source-map-support.

@nbransby
Copy link

I did read it, I assumed by " I recommend you compile the JavaScript files with source maps and execute those directly instead" you meant don't use ts-node.

I did look at that project before but looked like far more effort to setup compared to ts-node, i'll stick with switching configs for now

@blakeembrey
Copy link
Member

Yes, that's exactly what I recommend. I'm not sure what you're asking now, sorry. That project is only one line - you asked for source map support with stack traces?

@nbransby
Copy link

yes will take another look thanks

@amcdnl
Copy link
Author

amcdnl commented Jun 30, 2016

'm coming back to this after a bit, have a few comments since first started...

TypeScript still does not have access to the source maps of ts-node - they are in memory\

@blakeembrey Are you not saving the files to disk at all? I know babel/register actually does that.

The main problem here I think is that VSCode seems to require access to a .js file on disk, but ts-node doesn't emit the generated code to a file. The TypeScript inlineSources compiler options could've perhaps provided a workaround, unfortunately according to the docs...

@enlight you should check this out, looks like it has it now microsoft/vscode#2803

I'd recommend checking out https://github.com/evanw/node-source-map-support.

@blakeembrey would be worth considering building this into ts-node.

I have a working debugger just fine with VS Code, but you need to emit the .js and source map files for VS Code to consume (and configure outDir) and not use ts-node.

@blakeembrey so I have to ask if this is necessary what is the point of this project? ;)

@blakeembrey
Copy link
Member

blakeembrey commented Jun 30, 2016

Are you not saving the files to disk at all?

No, that's the entire point. Babel does it as a cache, but a cache doesn't help much with TypeScript since it's not a single file cache and requires the entire project loaded anyway for compilation errors. In --fast mode, it's possible we could do it. On top of this, if VS Code (or other debuggers) can use the source maps from files while executing the rest in memory, I'm happy to make that change - it seems like a great fix to me.

would be worth considering building this into ts-node.

It has been since the first release.

so I have to ask if this is necessary what is the point of this project?

Lots of people have different use-cases to you and may not use an IDE debugger. For instance, I've never really used it (for something I'd use ts-node for). I tend to use ts-node for running tests without needing to compile them and restructure the entire project with fixtures.

@amcdnl
Copy link
Author

amcdnl commented Jun 30, 2016

Thanks for clarifying those details! I'm just trying to understand the use cases for the project given the hurdles.

I hate having to have tool and workflow for build/etc when this theoretically could be done on the fly 😞

@blakeembrey
Copy link
Member

Understandable - I think it'd be valuable to check if generating the source map contents into a temp file would fix this. I'll make that change when I get a chance, probably just rewriting contents into tmp/<sha> files for caching and lookup later. I really feel it might fix this, so thanks for the idea!

@amcdnl
Copy link
Author

amcdnl commented Jul 1, 2016

@blakeembrey awesome!! Let me know and i'll give it a try on my demo project I'm working on.

For reference, on the Babel page you can see BABEL_CACHE_PATH variable which sets the path BABEL_CACHE_PATH=/foo/my-cache.json babel-node script.js. By default I think it saves them in node_modules that being local or global.

@jeffijoe
Copy link

Any progress on this? I'm using the CLI with nodemon and ts-node + attach in VSCode

@blakeembrey
Copy link
Member

I went ahead and built #148. Feel free to test it and let me know if it works.

I have a suspicion that it won't though. VS Code needs to be able to discover the source map file. If it could do that, it should have been doing that already with previous versions. The issue is that VS Code needs access to both .js and .js.map files to work properly with debugging.

@amcdnl
Copy link
Author

amcdnl commented Jul 20, 2016

@blakeembrey couldn't you inline the sourcemaps?

@evgenyt1
Copy link

evgenyt1 commented Jan 31, 2018

@cspotcode I had to replace "runtimeArgs" with "args" to make it work and add debugger statement as @cgatian
Otherwise --inspect=12400 --debug-brk args are passed after foo.ts and are ignored by ts-node

node: 8.9.4
ts-node: 4.1.0
vs-code: 1.9.3

@Xotabu4
Copy link

Xotabu4 commented Feb 19, 2018

For debugging protractorJS tests this works:

        {
            "type": "node",
            "request": "launch",
            "name": "Working thru node",
            "program": "${workspaceFolder}/node_modules/.bin/protractor",
            "args": [
                "./jasminejs/protractor.conf.js",
                "--directConnect=true"
            ],
            "protocol": "inspector",
            "sourceMaps": true,
            "console": "internalConsole",
            "outputCapture": "std"
        }

The only JS file - is protractor.conf.js, and first line - require('ts-node').register();

tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es6",
    "sourceMap": true,
    "inlineSourceMap": true,
    "outDir": "./built"
  },
  "exclude": [
    "node_modules/"
  ]
}

@peternann
Copy link

peternann commented Mar 17, 2018

Can I strongly suggest (/beg) that the 'current, best' way to setup VSCode debugging with ts-node is described in the main README?

VSCode is very widely used for Typescript dev.
ts-node is awesome during dev.
Both working together would be SWEET, but it's BLACK MAGIC to get it going!
There is a TON of partial/old/incorrect information floating around...

An official 'Hello World' debugging setup would give ts-node much more traction with devs I expect... If they can't get it working straight away with step-through debugging - You've lost 80% of folks right there...

Which is to say - I've tried several stated solutions from above, and elsewhere, but can't get breakpoints to work reliably (if at all) with ts-node. I guess I will head down the "tsc --watch" path to get a vague equivalent to ts-node...

@cspotcode - Any chance you could pop up a complete, working 'Hello World' project with debugging support and VSCode config on github? I'll send you $20 for your trouble. Seriously...

@blakeembrey
Copy link
Member

I can check but I'm not sure it should be very complicated to get started. Just add ['-r', 'ts-node/register'] to the default node.js configuration? I don't really use this myself but would accept a PR that adds the example to the README.

@blakeembrey
Copy link
Member

Just verified it working locally by creating a new project. All I did is below. Can someone confirm this?

        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "runtimeArgs": [
                "-r",
                "ts-node/register"
            ],
            "args": [
                "${workspaceFolder}/index.ts"
            ]
        }

@peternann
Copy link

peternann commented Mar 22, 2018

I'm still getting patchy breakpoint behaviour. It seems to work reliably in the primary file (index.ts), but not in other imported files.

Interestingly, it works somewhat more reliably after a restart of VSCode.
I'm testing a very short-lived script - It feels a bit like a race condition during startup perhaps.
Strangely, WHETHER OR NOT the breakpoint happens to work in any one run, hovering over the breakpoints list in VSCode, after running, always says "Breakpoint ignored because generate code not found (source map problem?)". Yes, it even says that on the rare occasion that IT WORKS.

Breakpoint debugging is simply not working reliably for me I'm afraid.
Bummer.

Is any special content required in tsconfig.json? And/Or is it necessary for it to be non-existant?

@blakeembrey
Copy link
Member

blakeembrey commented Mar 22, 2018

@peternann Can you share the configuration(s) you have tried? Also possible node.js and ts-node versions? I'm not sure how there could be a race condition unless you are using different configuration such as setting your own port. In which case you should check out https://code.visualstudio.com/docs/nodejs/nodejs-debugging since it's all the same, just with two lines added for ts-node/register.

@s-KaiNet
Copy link

Just verified it working locally by creating a new project. All I did is below. Can someone confirm this?

Works well for me on node 8.10, however on node 6.x breakpoints never hit. Maybe that's the case for other folks.

@s-KaiNet
Copy link

s-KaiNet commented Mar 24, 2018

Works well for me on node 8.10, however on node 6.x breakpoints never hit. Maybe that's the case for other folks.

UPDATE: well, breaks work in an initial file (index.ts for example), however, don't work in all imported files :( (Breakpoint ignored because generate code not found (source map problem) - exactly like @peternann mentioned

@s-KaiNet
Copy link

s-KaiNet commented Mar 24, 2018

Created reproduction repository - here:

  1. Clone, npm i
  2. Add breaks in index.ts and parser.ts, F5 -> doesn't work in parser.ts

node 8.10 npm 5.7.1

UPDATE: the funny thing is, that it works exactly the same with generated .js files (break hits in index.js, but not in parser.js). Configuration is below:

{
	"type": "node",
	"request": "launch",
	"name": "node",
	"program": "${workspaceFolder}/lib/index.js",
	"preLaunchTask": "build",
	"sourceMaps": true
},

So now it looks like vscode\TS issue? Or tsconfig should be tweaked... I'm confused

UPDATE2: verified on my old project with ts-node@3.x - the same behaviour, however it worked a few months ago..

UPDATE3: left a comment here as well..

@s-KaiNet
Copy link

So it looks like vscode bug... superannoying!

@s-KaiNet
Copy link

Installed 1.20 from here - everything works! ts-node, node, breaks, everything!

@Kamilius
Copy link

Kamilius commented Mar 29, 2018

@s-KaiNet nope, it still doesn't work for me though (angular-cli protractor and vscode). Tests are launching, but breakpoints are greyed-out with a message "Breakpoint ignored because generated code not found (source map problem?)".

@s-KaiNet
Copy link

@Kamilius hmmm strange...
Did it work before?
Do you have 1.20 installed?

If the answer is yes to both questions, then I don't know the reason why it's still doesn't work for you. For me, 1.20 automagically fixed all issues.

@davidwesst
Copy link

davidwesst commented Mar 29, 2018

Just a quick update for people. Looking through the bug mentioned by @s-KaiNet, if you're using VS Code 1.21.1, you will need to follow the workaround.

The fix is in place for the next build, but unless they release a 1.21.2, we won't see the fix until 1.22.

I can confirm that I have everything working as expected in 1.22-insiders with the following launch.json

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Run Tests",
            "cwd": "${workspaceFolder}",
            "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
            "args": [
                "--no-timeouts",
                "--colors",
                "--recursive",
                "--inspect-brk",
                "${workspaceFolder}/test/**/*.spec.ts",
                "--require", "ts-node/register"
            ],
            "stopOnEntry": false,
            "internalConsoleOptions": "openOnSessionStart",
            "sourceMaps": true,
            "protocol": "inspector",
            "outFiles": [
                "${workspaceFolder}/test/**/*.*"
            ]
        }
    ]
}

@Kamilius I suggest trying your project using VS Code Insiders build, just to see if it works as expected.

@Kamilius
Copy link

Kamilius commented Mar 30, 2018

@s-KaiNet, I don't know if it worked previously, as I've just started writing and running those tests
@s-KaiNet @davidwesst thanks, I am already using insiders version, which is currently Version 1.22.0-insider (1.22.0-insider), also I'm using ts-node inside protractor's onPrepare(). My project is generated using angular-cli and this configuration comes by default:

  onPrepare() {
    require('ts-node').register({
      project: './e2e/tsconfig.e2e.json'
    });
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }

@davidwesst workaround you've suggested, for ts-node users, proposes to reapply all breakpoints, but it doesn't work for me. Breakpoints stay greyed out after reapplying operation.

Here's my launch.json configuration:

  {
      "type": "node",
      "request": "launch",
      "name": "ng e2e",
      "cwd": "${workspaceFolder}/angular",
      "program": "${workspaceFolder}/angular/node_modules/protractor/bin/protractor",
      "protocol": "inspector",
      "args": ["${workspaceFolder}/angular/protractor.conf.js"],
      "stopOnEntry": false,
      "sourceMaps": true,
      "runtimeExecutable": "~/.nvm/versions/node/v7.9.0/bin/node",
      "runtimeVersion": "7.9.0",
      "outFiles": [
        "${workspaceFolder}/**/e2e/**/*.js"
      ]
    }

Version of node is set to 7.9.0, as default 8.9.3 is not launching e2e tests at all, only showing warning:

(node:7523) [DEP0062] DeprecationWarning: `node --debug` and `node --debug-brk` are invalid. Please use `node --inspect` or `node --inspect-brk` instead.

@davidwesst
Copy link

@Kamilius -- My apologies as I didn't see this until just now!

Well, 1.22.1 is already out, so hopefully that resolves the issue in the long-term. The answer I found for the breakpoint thing was you needed to follow the following to "reapply all breakpoints":

  • Start your debugger
  • Break on first line
  • _Now disable and re-enable all breakpoints
  • You should hopefully hit the next breakpoint
  • Repeat every time you debug

Again, hopefully this is fixed in the new version of Code that is out, but that was my little workaround.

@peternann
Copy link

peternann commented May 1, 2018

I am still having no luck with this. I gave up on my old project. Figured it had something weird.
But I'm now on a new project, on a different computer, and a different OS, and having the same troubles.

As requested by @blakeembrey, here is my launch config:

        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "runtimeArgs": [
                "-r",
                "ts-node/register"
            ],
            "args": [
                "${workspaceFolder}/index.ts"
            ]
        }

Yes, that is byte-for-byte what was suggested.
I am using vscode 1.22.2, on Windows 7.
Using versions: Node=8.10, ts-node=6.0.2, typescript=2.8.3
(Latest at time of writing)

Breakpoints in the top file (index.ts) work fine, (Even though they report "Breakpoint ignored because generated code not found (source map problem?)."

The other breakpoints show the same text on hover, but are grayed out and the breakpoint circle is empty. They go gray as soon as I launch, by the time they hit my test breakpoint in the top file.

The disable/reenable/Reapply All tricks do not work for me.

This is driving me bananas.

Does the contents of tsconfig.json matter? Here's mine right now after minimizing it:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "outDir": "dist",
    },
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

'tsc' completes happily, silently

Any new ideas out there?

@iammelvin
Copy link

@blakeembrey Thanks for the solution it works !

@phil294
Copy link

phil294 commented Aug 19, 2018

For attaching, the process is pretty much the same. package.json:

"scripts": {
    "dev": "node --inspect $(npm bin)/ts-node index.ts"

and in launch.json the typical

"type": "node",
"request": "attach",
"protocol": "inspector",
 "port": 9229

@foxundermoon
Copy link

Unverified breakpoint

when start by nodemon --config nodemon.json --exec \"node --inspect=56386 --nolazy -r dotenv/config -r ts-node/register src/app.ts\"

without nodemon ,the breakpoint is ok

@tomitrescak
Copy link

tomitrescak commented Nov 12, 2018

I just paste here couple solutions that work nicely:

Launch

{
      "name": "TS Node",
      "type": "node",
      "request": "launch",
      "env": {
        ... whatever
      },
      "args": ["./src/server/index.ts"],
      "runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}",
      "protocol": "inspector"
    }

Attach With Forever

this is particularly cool, as the forever automatically restarts the process and debugger automatically re-attaches 👍

{
      "name": "Forever",
      "type": "node",
      "request": "attach",
      "sourceMaps": true,
      "restart": true,
      "port": 9229,
      "cwd": "${workspaceRoot}",
      "protocol": "inspector"
    }

And the command

forever -a --watch --watchDirectory ./src/server --uid youruid -c \"node --nolazy -r ts-node/register --inspect=9229\" src/server/index.ts

@zwhitchcox
Copy link

{
      "name": "TS Node",
      "type": "node",
      "request": "launch",
      "env": {
        ... whatever
      },
      "args": ["./src/server/index.ts"],
      "runtimeArgs": ["--nolazy", "-r", "ts-node/register"],
      "sourceMaps": true,
      "cwd": "${workspaceRoot}",
      "protocol": "inspector"
    }

This did not work for me...the only think that has worked is manually compiling the typescript files and then manually running the debugger

@PuzoLiang
Copy link

Just verified it working locally by creating a new project. All I did is below. Can someone confirm this?

        {
            "type": "node",
            "request": "launch",
            "name": "Launch Program",
            "runtimeArgs": [
                "-r",
                "ts-node/register"
            ],
            "args": [
                "${workspaceFolder}/index.ts"
            ]
        }

thank you very much

@millsp
Copy link

millsp commented Sep 6, 2019

Hey @blakeembrey, do you know if this is still working correctly?
Because I am able to debug using breakpoints, but in some cases, the breakpoint is just ignored.
This seems to happen when a breakpoint is placed in a file that is not directly run. I also tried to add --nolazy but without success. Should I just transpile?

{
	"launch": {
		"configurations": [
			{
				"name": "Debug Current",
				"type": "node",
				"request": "launch",
				"args": [
					"${fileBasename}"
				],
				"runtimeArgs": [
					"-r",
					"ts-node/register"
				],
				// "sourceMaps": true,
				"cwd": "${fileDirname}",
				"protocol": "inspector",
				"outputCapture": "std",
			},
		],
		"compounds": []
	}
}

EDIT: It does work, if I place a breakpoint in the file that is run, strangely. Any idea?
EDIT: I also tried to do this with the config you provide, and the result is the same.

@millsp
Copy link

millsp commented Oct 14, 2019

nevermind, it seems to be related to microsoft/vscode-chrome-debug-core#533

@GuillaumeDesforges
Copy link

If anybody lands here, I'd advise using ts-node-dev

example: https://gist.github.com/GuillaumeDesforges/bf7383f8403e1683b2b9467db3964185

@protoEvangelion
Copy link

Thank you @GuillaumeDesforges I tried like a 1000 different ways and this was the only one that worked for my use case 😓

{
            "name": "runit",
            "type": "node-terminal",
            "request": "launch",
            "command": "ts-node-dev --inspect -T -O '{\"esModuleInterop\": true}' --skip-project my-scripts/migrate.ts my-scripts/a",
            "cwd": "${workspaceFolder}"
},

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
external research Needs design work, investigation, or prototyping. Implementation uncertain. wontfix you can do this Good candidate for a pull request.
Projects
None yet
Development

No branches or pull requests