Babel + Mocha stack traces report wrong line numbe

2019-07-02 16:44发布

问题:

When using Babel 6 and Mocha, the stack trace reports a wrong line number. I am pretty sure this is because the transpiling adds extra code. This is new behavior in Babel 6 vs. Babel 5.x for me. Does anyone have a solution on how to fix this when using Mocha for unit tests?

Here is my .babelrc config:

{
  "ignore": [
    "node_modules",
    "bower_components"
  ],
  "presets": [
    "es2015",
    "react"
  ],
  "plugins": [
    "transform-react-constant-elements",
    "syntax-async-functions",
    "transform-regenerator"
  ]
}

Note: this is happening whether or not I require('babel-polyfill') at the entry point of my app.

A sample stack trace looks like this:

TypeError: Cannot read property 'should' of undefined
    at _callee2$ (test/unit/index.test.js:217:34)
    at step (test/unit/index.test.js:27:284)

回答1:

Sourcemaps and retainLines:true option. Here's an example Gulp task:

const babel = require('gulp-babel');
const sourcemaps = require('gulp-sourcemaps');

gulp.task('babel', done =>
    gulp.src('src/**/*.es6')
    .pipe(sourcemaps.init())
    .pipe(babel({
        presets: ['es2015', 'stage-0'],
        retainLines: 'true',
    }))
    .pipe(sourcemaps.write('.', {
        sourceRoot: 'src'
    }))
    .pipe(gulp.dest('lib')));

You also have to have

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

at the top of your compiled code (just the entry point, i.e. the "main" file as specified in your package.json)