Search code examples
javascriptreactjsgulpbrowserifybabeljs

Can I use both ES6 and ES5 in the same React codebase?


I have the following gulpfile.js:

var gulp = require('gulp');
var browserify = require('gulp-browserify');
var concat = require('gulp-concat');

gulp.task('browserify', function() {
    gulp.src('js/ScheduleMain.js')
      .pipe(browserify({transform:'reactify'}))
      .pipe(concat('ScheduleMain.js'))
      .pipe(gulp.dest('static/dist/js'));
    gulp.src('js/ConfidenceMain.js')
      .pipe(browserify({transform:'reactify'}))
      .pipe(concat('ConfidenceMain.js'))
      .pipe(gulp.dest('static/dist/js'));
});

gulp.task('default',['browserify']);

gulp.task('watch', function() {
    gulp.watch('src/**/*.*', ['default']);
});

As you can see I have two source files that need transforming. ScheduleMain.js is written in es5 and builds fine. I want to write my new application (ConfidenceMain.js) in es6 and possible transform it to es5 for build. I am a bit confused on how to do this (or rather if it is at all recommended).

Bottom line: Can I move forward with new react projects written in es6 syntax despite having es5 code previously for other projects in the same code base?


Solution

  • Yes, you can mix both ES6 and ES5 - ES6 is fully backwards compatible, so essentially you could think of your entire app as ES6, but only use the new syntax and functionality in new code.

    You would need to add a transpilation step to your gulp pipeline to pass your code through babel and compile it down to ES5. Something like this:

    var gulp = require('gulp');
    var browserify = require('gulp-browserify');
    var concat = require('gulp-concat');
    var babel = require('gulp-babel');
    
    gulp.task('browserify', function() {
        gulp.src('js/ScheduleMain.js')
          .pipe(browserify({transform:'reactify'}))
          .pipe(concat('ScheduleMain.js'))
          .pipe(gulp.dest('static/dist/js'));
        gulp.src('js/ConfidenceMain.js')
          .pipe(babel())
          .pipe(browserify({transform:'reactify'}))
          .pipe(concat('ConfidenceMain.js'))
          .pipe(gulp.dest('static/dist/js'));
    });
    
    gulp.task('default',['browserify']);
    
    gulp.task('watch', function() {
        gulp.watch('src/**/*.*', ['default']);
    });
    

    Note that the code above wouldn't transpile ScheduleMain.js but you could easily do that if you wanted, to enable the use of ES6 features going forwards - just pipe it through babel() in the same way.

    Note that babel will require some configuration - the documentation will guide you through this. You'll want the es2015 and react presets.

    Edit: Given your use of browserify, a cleaner approach might be to use the babelify transform instead:

    gulp.src('js/ConfidenceMain.js')
      .pipe(browserify({transform:'babelify'}))
      .pipe(concat('ConfidenceMain.js'))
      .pipe(gulp.dest('static/dist/js'));