VSCode断点无法在gulp sourcemaps生成的sourcemap的typescript中工作

VSCode断点无法在gulp sourcemaps生成的sourcemap的typescript中工作,typescript,gulp,visual-studio-code,gulp-sourcemaps,Typescript,Gulp,Visual Studio Code,Gulp Sourcemaps,我在一个子目录routes中有一个typescript文件users.ts gulpfile.js中的gulp代码: var tsProject = ts.createProject(tsConfigFile); return tsProject.src() .pipe(sourcemaps.init()) .pipe(ts(tsProject)) .js .pipe(sourcemaps.write('.', {includeContent: false, so

我在一个子目录
routes
中有一个typescript文件
users.ts

gulpfile.js
中的gulp代码:

var tsProject = ts.createProject(tsConfigFile);
return tsProject.src()
    .pipe(sourcemaps.init())
    .pipe(ts(tsProject))
    .js
    .pipe(sourcemaps.write('.', {includeContent: false, sourceRoot: ''})) 
    .pipe(gulp.dest('.'));
gulp sourcemaps
生成的源地图不适用于VSCode:

{"version":3,"sources":["routes/users.ts"],"names":[], "mappings":"...","file":"routes/users.js","sourceRoot":""}
tsc
生成的源映射在VSCode中工作正常:

{"version":3,"file":"users.js","sourceRoot":"","sources":["users.ts"],"names":[], "mappings":"..."}
VSCode断点与由
tsc
生成的源映射配合使用


因此,如何配置
gulp typescript/gulp sourcemap
以生成与
tsc
相同的sourcemap?

这与
将sourceRoot函数添加到
源映射。写入(…)

假设您的
.ts
文件位于项目的
src
文件夹中,
sourcemaps
管道如下所示:

.pipe(sourcemaps.write('.', {
           sourceRoot: function(file){ return file.cwd + '/src'; }
      }))

在使用v-andrew方法构建源映射路径的计算机上,源映射路径将是正确的。但是,如果要在多台计算机上编译一次sourcemaps,请使用相对文件路径:

var path = require('path');

...

.pipe(sourcemaps.write('.', {
  includeContent: false,
  sourceRoot: function(file) {
    var fullPath = path.join(file.cwd, file.path);
    return path.relative(fullPath, file.base);
  },
}))

我在Windows上使用gulp sourcemaps 2.6.1,@Westy92的解决方案不起作用(不再?),因为file.path返回绝对文件路径(包括文件名):


被接受的答案是正确的,但是我花了一些时间才意识到为什么这样做有效&如何根据我的特定环境调整答案(在我的情况下,我需要去掉
/src
后缀)

如果检查生成的源映射(这仅在输出到映射文件时有效,例如,
sourcemaps.write('.')
),您应该在json对象中看到两个字段:
sources
sourceRoot
,有两件事需要确保:

  • sourceRoot
    应为绝对路径
  • sources
    中的每个路径都应与
    sourceRoot
    组合,以形成源文件的绝对路径
  • 如果#1不为真,则路径在某些情况下有效,而在其他情况下无效(一些工具解析相对于源映射文件的相对路径,其他工具基于工作区根、cwd或其他路径)

    如果#2不正确,您的工具将在错误的位置查找源文件


    另一个提示:请记住,更改gulpfile不会触发重新运行监视模式或清除任何文件缓存,因为源文件没有更改。

    管道(ts(tsProject))之后调用
    .js
    是什么?
    ?请看,
    在`pipe(ts(tsProject))之后调用.js
    ,我和OP有相同的问题(也适用于TSC生成的源地图),不幸的是,这并不能解决问题。确认了这一点。@pyrho请确保“/src”部分相对于项目的根映射到项目的根。您可能需要使用其他值,如“”、或“/src/server”等。您能发布gulpfile.js和项目布局的相关部分吗?谢谢!好的,我想我已经找到了e问题。使用sourceRoot可以很好地工作。但是出于某种原因,gulp typescript会将文件名小写,这会破坏VSCode的文件映射,请参阅。谢谢。
    var path = require('path');
    
    ...
    
    .pipe(sourcemaps.write({
      includeContent: false,
      sourceRoot: function(file) {
        return path.relative(path.dirname(file.path), file.base);
      },
    }))