Gulp sourcemaps with TypeScript and Babel

 ̄綄美尐妖づ 提交于 2019-12-04 05:44:34

Update

It appears that the specific issue in this question is related to Babel's incorrect source map generation for files which are not in the working directory. There is already an issue filed here.

For a vinyl File object like

new File({
  cwd: '.',
  base: './test/',
  path: './test/some/file.js'
  ...
});

the generated source map should have something like

{
  ...
  "sources": ["some/file.js"]
  ...
}

but gulp-babel gives

{
  ...
  "sources": ["file.js"]
  ...
}

This causes the Typescript source maps and Babel source maps to be incorrectly merged, but only when the file is deeper than the working directory.

While this issue is being resolved, I recommend targeting ES5 with Typescript and bypassing Babel completely. This produces correct source maps.

gulp.task('build', function () {
  return gulp.src('src/server/**/*.ts')
    .pipe(sourcemaps.init())
    .pipe(typescript({
      noImplicitAny: true,
      removeComments: true,
      preserveConstEnums: true,
      target: 'es5',
      module: 'commonjs'
    }))
    .pipe(sourcemaps.write('.', { sourceRoot: 'src/server' }))
    .pipe(gulp.dest('build/server'));
});

Previous Answer

You are close, but there are a couple mistakes I noticed in your configuration:

  1. "module": "commonjs" is incompatible with "target": "es6". Output ES6 modules with Typescript and let Babel transpile them to CommonJS.
  2. "outDir" is not necessary when using Gulp since you are working with a stream. Intermediate results (i.e. results of Typescript) are not written to disk at all.
  3. "sourceMap": true is not necessary together with Gulp sourcemaps.

I have created a project which compiled for me, with babel@6.1.18 and typescript@1.6.2.

Directory structure

.
├── gulpfile.js
└── src
    └── server
        ├── one.ts
        └── two.ts

one.ts

export class One {};

two.ts

import { One } from './one';

export class Two extends One {}

gulpfile.js

I have inlined all configurations for terseness, but you should be able to use config files just as easily.

var gulp = require('gulp');

var sourcemaps = require('gulp-sourcemaps');
var typescript = require('gulp-typescript');
var babel = require('gulp-babel');

gulp.task('build', function () {
  return gulp.src('src/server/**/*.ts')
    .pipe(sourcemaps.init())
    .pipe(typescript({
      noImplicitAny: true,
      removeComments: true,
      preserveConstEnums: true,
      target: 'es6'
    }))
    .pipe(babel({
      presets: [ 'es2015' ]
    }))
    .pipe(sourcemaps.write('.', { sourceRoot: 'src/server' }))
    .pipe(gulp.dest('build/server'));
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!