首页 > 解决方案 > 无法在 VS Code 中设置断点调试节点 Typescript

问题描述

我看到了同样问题的其他问题,但我已经尝试了所有其他解决方案,但没有任何效果。

我有一个打字稿节点应用程序,我正在尝试在 VSCode 中进行调试。

我的 launch.json 是

 "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      "name": "Attach",
      "port": 5858,
      "sourceMaps": true,
      "outFiles": ["${workspaceRoot}/build/**/*.js"]
    }
  ]

这很好地附加到我的应用程序。我可以暂停和恢复,一切正常,但我无法进入代码或设置断点。

我正在通过 gulp nodemon 运行我的应用程序

nodemon({
    script: 'build/server.js',
    watch: 'src',
    ext: 'ts',
    tasks: ['clean', 'compile'],
    exec: 'node --debug'
});

控制台输出

调试器监听 [::]:5858

现在,当我尝试设置断点时,它说

未验证的断点,由于找不到生成的代码而忽略了断点(源映射问题?)。

更新;

我也尝试过使用webRoot其他帖子所建议的项目,键入验证抱怨说Property webRoot is not allowed.,我尝试继续无济于事。

我正在运行 Node v6.11.5 和 VS Code v1.23.0

我在帖子中看到人们呼吁运行 .scripts 标记以获取更多帮助解决的信息,但是当我通过.scripts在调试控制台中键入时它说invalid expression: unexpected token .

我的 tsconfig.json 是

"compilerOptions": {
    "outDir": "build",
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "typeRoots": ["node_modules/@types"]
  },

然而; 我的构建文件夹中没有.js.map文件。我正在通过 gulp-typescript 运行构建,如下所示

gulp.task('compile', () => {
    tsProject = ts.createProject('tsconfig.json');
    let tsResult = tsProject.src().pipe(ts());

    return merge([
        tsResult.dts.pipe(gulp.dest('build/definitions')),
        tsResult.js.pipe(gulp.dest('build'))
    ]);
});

根据建议,我还添加了以下 gulp 任务

gulp.task('jsMaps', function() {
    gulp.src('build/**/*.js')
      .pipe(sourcemaps.init())
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('build'));
  });

并确认我的构建 .js 文件具有内联编写的源映射,看起来像//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIiwic291cmNlc...........,但是在尝试设置断点时我仍然遇到相同的错误。

标签: node.jstypescriptdebuggingvisual-studio-codevscode-debugger

解决方案


为了调试打字稿,您需要生成源映射文件。确保以下内容在您的 中tsconfig.json,您应该会看到.js.map在您的构建目录中生成的文件。

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

使用 gulp-typescript:

gulp-typescript建议应该使用gulp-sourcemaps来生成源映射。

这是我在创建.js.map断点处中断的文件时所做的 gulp 任务。在这个 gulp-typescript 问题中找到

var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var path = require('path');
var ts = require('gulp-typescript');

gulp.task('compile', () => {
    tsProject = ts.createProject('tsconfig.json');
    let tsResult = tsProject.src()
        .pipe(sourcemaps.init())
        .pipe(tsProject());

    tsResult.js
        .pipe(sourcemaps.write({
          sourceRoot: function (file) {
            var sourceFile = path.join(file.cwd, file.sourceMap.file);
            return path.relative(path.dirname(sourceFile), file.cwd);
          }
        }))
        .pipe(gulp.dest('build'));
});

推荐阅读