Transform ES5 code to ES6 at runtime

To change ES5 to ES6 you can use this https://www.npmjs.com/package/xto6

You have to install it

npm install -g xto6

And then just:

xto6 es5.js -o es6.js

There is also gulp plugin https://www.npmjs.com/package/gulp-xto6:

var gulp = require('gulp');
var xto6 = require('gulp-xto6');

gulp.task('default', function () {
  return gulp.src('path/to/fixtures/es5/*.js')
    .pipe(xto6())
    .pipe(gulp.dest('path/to/fixtures/es6/'));
});

The best idea is to go into the source code of Lebab

Open bin/file.js. Read all the lines to understand that script.

The interesting part is the following:

  var transformer = new Transformer({transformers: transformers});
  transformer.readFile(file[0]);
  transformer.applyTransformations();
  transformer.writeFile(program.outFile);

More specificaly transformer.applyTransformations();

Let's open /src/transformer.js

In this file I see some usefull functions :

  /**
   * Prepare an abstract syntax tree for given code in string
   *
   * @param string
   */
  read(string) {

    this.ast = astGenerator.read(string, this.options);

  }

So you can use the transformer with a string of code (not a file)

Now you can apply the transformations "ES5 to ES6"

  /**
   * Apply All transformations
   */
  applyTransformations() {

    for (let i = 0; i < this.transformations.length; i++) {
      let transformation = this.transformations[i];
      this.applyTransformation(transformation);

    }

And then, recast it into string

  out() {
    let result = recast.print(this.ast).code;

    if(this.options.formatter) {
      result = formatter.format(result, this.options.formatter);
    }

    return result;
  }

Summary

var transformer = new Transformer({});
transformer.read('var mySourceCode = "in ES5"');
transformer.applyTransformations();
console.log(transformer.out());

JSFiddle demo here

If you don't want all transformations, you can choose what you want with options:

var transformers = {
  classes: false,
  stringTemplates: false,
  arrowFunctions: true,
  let: false,
  defaultArguments: false,
  objectMethods: false,
  objectShorthands: false,
  noStrict: false,
  importCommonjs: false,
  exportCommonjs: false,
};

var transformer = new Transformer({transformers: transformers});

JSFiddle demo with options