0

I have a build process using gulp and babel, but babel is throwing me this weird duplicate function names all over my app.

The error in Chrome is: ReferenceError: changeScale is not defined

The original code:

changeScale = function(value) {
    if (value >= 1000000) return value/1000000 + 'M';

    if (value >= 1000) return value/1000 + 'k';

    return value;
};

The code after gulp and babel:

changeScale = function changeScale(value) {
    if (value >= 1000000) return value / 1000000 + 'M';

    if (value >= 1000) return value / 1000 + 'k';

    return value;
};

Notice the duplicate function name?

My gulp task:

var gulp         = require('gulp');
var gutil        = require('gulp-util');
var bower        = require('bower');
var babel        = require("gulp-babel");
var concat       = require('gulp-concat');

gulp.task('js', function() {
  gulp.src('./www/app/**/*.js')
  .pipe(babel())
  .pipe(concat('app.js')).on('error', errorHandler)
  .pipe(gulp.dest('./www/js/'));
});

And my .babelrc file: { "presets": ["es2015"] }

loganfsmyth
  • 135,356
  • 25
  • 296
  • 231
Mathius17
  • 2,132
  • 2
  • 17
  • 33
  • 1
    They're not weird, they're ES6: All anonymous function expressions assigned to something are getting named. And no, they are not the cause of your error. Show us where you are trying to call this function, and in which line you get that exception. – Bergi Mar 08 '16 at 01:33

2 Answers2

4

Your code is assigning an anonymous function to a variable called changeScale, but without the var keyword you're creating a global variable. The output from Babel is presumably set to use ES5 strict mode, which disallows defining global variables without the var keyword, so Chrome is throwing a ReferenceError as that variable has never been defined.

You can fix this by either changing your code to var changeScale =, or by changing from using a variable to using a function declaration function changeScale() {}. Either will work fine, and you can read about the differences here.

As an aside, the duplicated function names you're seeing here aren't an issue – it's perfectly valid to assign a named function to a variable, and it can make it easier to debug your code as debuggers will be able to show you that name instead of just listing it as an anonymous function.

Peter Josling
  • 726
  • 6
  • 6
0

You can set babelrc browsers list's IE version to 11 can change this. Like ["> 5%", "last 2 versions", "IE 11"]

Pader
  • 17
  • 2