如何参考 Nest.js 中的打字稿源打印堆栈跟踪

Ale*_*scu 17 stack-trace console.log nestjs

我正在开发一个 Nest.js 服务器,并希望能够在控制台(例如 console.log)中打印有用的堆栈跟踪。默认情况下,它返回对编译源 (.js) 中行号的引用。这对调试没有用,因为它缺少对原始源文件 (.ts) 中行号的引用

这是我的 tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "_baseUrl": "./",
    "incremental": true
  },
  "exclude": ["node_modules", "dist"]
}
Run Code Online (Sandbox Code Playgroud)

.map 文件也在 dist 文件夹中生成,尽管在控制台中检查堆栈跟踪时它似乎没有用。

Jay*_*iel 23

出于可见性目的:添加source-map-support NPM 包允许在堆栈跟踪中跟踪打字稿文件。

它可以在命令行上添加node -r source-map-support/register fileToRun.js或以编程方式添加

import * as sourceMapSupport from 'source-map-support';
sourceMapSupport.install();
Run Code Online (Sandbox Code Playgroud)

或者

import { install } from 'source-map-support';
install();
Run Code Online (Sandbox Code Playgroud)

或使用 ES6 模块

import 'source-map-support/register';
Run Code Online (Sandbox Code Playgroud)

  • 您只需要将其添加到您的“main.ts”或如上所述的命令行中。 (2认同)
  • 在打字稿中不要忘记`npm i --save-dev @types/source-map-support` (2认同)

Tor*_*hel 5

如果我还添加了一个,我才能使其正常工作

webpack.config.js

将文件复制到 NestJS 项目的根目录中,内容如下:

// webpack.config.js
module.exports = function(options) {
  return {
    ...options,
    devtool: 'inline-source-map',
  }
}
Run Code Online (Sandbox Code Playgroud)

有了这个文件,就可以在将 NestJS 源代码转换为 main.js 时根据需要配置 Webpack。

在 main.ts 中,我添加了以下几行,如上面答案中所述:

import * as sourceMapSupport from 'source-map-support';
sourceMapSupport.install();
Run Code Online (Sandbox Code Playgroud)

瞧,它的工作和精确的 Typescript 文件以及行号显示在控制台堆栈跟踪中。