在node/nodemon中是否有源映射支持typescript?

k0p*_*kus 29 javascript node.js typescript nodemon

我有一个用typescript @ 2编写的节点项目.

我的tsconfig已sourceMap设置为true*.map.js生成文件.当我*.js通过node或执行我编译的JavaScript文件时nodemon,我只看到相对于js文件的错误消息,而不是映射的typescript文件; 我认为它完全被忽略了.

sourceMap仅支持用于浏览器的支持?或者我可以将它与node或nodemon一起使用吗?如果是后者,我将如何启用它?

我想看到js文件中相对于typescript文件检测到的错误.

Ste*_*aul 24

我只是在我的快递应用程序中工作.

安装所需的库:

npm install --save-dev source-map-support

在您的入口点(例如app.ts):

require('source-map-support').install();

在您的工作中app.ts,您可能还需要更好地记录承诺中的错误:

process.on('unhandledRejection', console.log);

在你的tsconfig下面compilerOptions:

"inlineSourceMap": true

  • inlineSourceMap和sourceMap编译器选项互斥 (3认同)
  • 如果您将cli用法添加到您的答案中(如我自己指出的那样),我将接受您的答案并删除我的答案。(/sf/answers/4091864381/) (2认同)

k0p*_*kus 21

安装源地图支持:

npm install source-map-support
Run Code Online (Sandbox Code Playgroud)

(我也在生产中运行,因为它极大地帮助从发生错误时的日志中查找错误。我没有遇到过很大的性能影响,但您的体验可能会有所不同。)

添加到您的tsconfig.json

{
   "compilerOptions": {
      "sourceMap": true
   }
}
Run Code Online (Sandbox Code Playgroud)

运行 JavaScript 文件时,添加 require 参数:

nodemon -r source-map-support/register dist/pathToJson.js

node -r source-map-support/register dist/pathToJson.js
Run Code Online (Sandbox Code Playgroud)

或者,您在入口调用中添加:

require('source-map-support').install()
Run Code Online (Sandbox Code Playgroud)

但我发现这很乏味,这是具有多个入口点的项目。


旁注:mocha还支持--require/-r选项,因此要在 mocha 中获得源映射支持,您还可以使用它调用您的测试,例如类似于:

NODE_ENV=test npx mocha --forbid-only --require source-map-support/register --exit --recursive ./path/to/your/tests/
Run Code Online (Sandbox Code Playgroud)


mve*_*and 11

我发现这个npm模块似乎可以解决这个问题:

https://github.com/evanw/node-source-map-support

npm install source-map-support --save在节点项目的根目录下运行并添加import 'source-map-support/register'到main.ts或index.ts文件中.

而已.


Tre*_*son 8

这里的答案对于v12.12.0之前的 Node 版本是正确的,它添加了(实验性)--enable-source-maps标志。启用该功能后,源映射将应用于堆栈跟踪,而无需额外的依赖项。如本文所示,它包含生成的 .js 文件位置和源文件位置的行为略有不同且可能有益。例如:

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
Run Code Online (Sandbox Code Playgroud)

  • `NODE_OPTIONS=--enable-source-maps npm test` 是我正在寻找的命令 (5认同)

Ast*_*ear 8

对于 v12.12.0 及以上的 Node 版本, 运行 Node 时请使用 --enable-source-maps 标志。

示例:node --enable-source-maps main.js

不要为 v12.12.0 及以上的 Node 版本安装“source-map-support”


Bru*_*der 5

源地图支持与节点完美配合

您需要做的就是添加

"source-map-support": "0.4.11",
Run Code Online (Sandbox Code Playgroud)

dependenciesdev-dependenciespackage.json运行

npm install --save source-map-support
Run Code Online (Sandbox Code Playgroud)

在您的入口点ts文件中,只需在顶部添加即可

require('source-map-support').install()
Run Code Online (Sandbox Code Playgroud)

(注意:这是调用nodeJS require- 不需要源映射支持定义文件)