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

Is there source map support for typescript in node / nodemon?

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

我的 tsconfig 已将 sourceMap 设置为 true 并生成了 *.map.js 文件。当我通过 nodenodemon 执行我的转译 *.js JavaScript 文件时,我只看到与 js 文件相关的错误消息,而不是映射的打字稿文件;我认为它完全被忽略了。

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

我想查看从已执行的 javascript 文件中检测到的相对于原始打字稿文件的运行时错误。

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

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

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

就是这样。

源映射支持与 node

完美配合

您只需添加

"source-map-support": "0.4.11",

dependenciesdev-dependenciespackage.json 由 运行

npm install --save source-map-support

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

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

(注意:这是调用 nodeJS require - 不需要 source-map-support 定义文件)

for Node versions since v12.12, there is an .

我最近在我的 Express 应用程序中使用了它。步骤如下:

安装所需的库:

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

安装源映射支持:

npm install source-map-support

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

添加到您的tsconfig.json

{
   "compilerOptions": {
      "sourceMap": true
   }
}

当 运行ning 你的 JavaScript 文件时,添加要求参数:

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

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

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

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

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


旁注:mocha also supports the --require / -r 选项,因此要在 mocha 中支持 sourcemap,您还可以使用它调用您的测试,例如类似于:

NODE_ENV=test npx mocha --forbid-only --require source-map-support/register --exit --recursive ./path/to/your/tests/

此处的答案对于 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 之前的 Node 版本是正确的,它具有稍微不同但可能有益的行为,包括生成的 .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

对于 v12.12.0 的节点版本,当您 运行 节点时使用 --enable-source-maps 标志。

示例:节点 --enable-source-maps main.js

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