Is there source map support for typescript in node / nodemon?
Solution 1:
🚩 for Node versions since v12.12, there is an easier and better solution.
I recently got this working in my express app. Steps as follows:
Install the required library:
npm install --save-dev source-map-support
In your entry point (eg app.ts
):
require('source-map-support').install();
In your app.ts
, you may also require better logging for errors within promises:
process.on('unhandledRejection', console.log);
In your tsconfig
, under compilerOptions
:
"inlineSourceMap": true
Solution 2:
Install source map support:
npm install source-map-support
(I run in in production as well, as it immensely helps finding bugs from the logs of when an error an occurs. I did not experience a large performance impact, yet your experience may be different.)
Add to your tsconfig.json
:
{
"compilerOptions": {
"sourceMap": true
}
}
When running your JavaScript file, add the require parameter:
nodemon -r source-map-support/register dist/pathToJson.js
node -r source-map-support/register dist/pathToJson.js
Alternatively, you add in your entry call:
require('source-map-support').install()
yet I find this tedious is projects with multiple entry points.
Sidenote: mocha also supports the --require
/ -r
option, so to have the sourcemap support in mocha you can also call your tests with it, e.g. similar to:
NODE_ENV=test npx mocha --forbid-only --require source-map-support/register --exit --recursive ./path/to/your/tests/
Solution 3:
The answers here are correct for Node versions before v12.12.0, which added the (experimental) --enable-source-maps
flag. With that enabled, source maps are applied to stack traces without an additional dependency. As demonstrated in this article, it has the slightly different and possibly beneficial behavior of including both the generated .js file location and the source file location. For example:
Error: not found
at Object.<anonymous> (/Users/bencoe/oss/source-map-testing/test.js:29:7)
-> /Users/bencoe/oss/source-map-testing/test.ts:13:7
Solution 4:
I found this npm module which seems to do the trick:
https://github.com/evanw/node-source-map-support
run npm install source-map-support --save
at the root of your node project and add import 'source-map-support/register'
to your main.ts or index.ts file.
That's it.