ASP.NET, Aurelia and transpiling when building

In one of my previous posts on Aurelia, I set up Aurelia with ASP.NET, using jspm to load my scripts, and Babel to transpile the ES2015/2016 (previously called ES6/7) to ES5.

The problem is, this happens on-the-fly. This will reduce the speed of our app, as there is extra processing done when the user requests a page. Also, there is no reason to do this, as the scripts can be transpiled before deploying (i.e. when building our app in Visual Studio).

The solution is quite simple.

First, move all your ES2015 (previously called ES6) files out of your wwwroot folder (if you followed the steps I explained in my previous posts). Put them somewhere else, for example under the root of your project in a folder aurelia.

Open your jspm config.js file and add "modules" : "system" to the babelOptions part.

Then, I use Gulp to automatically call Babel when I build in Visual Studio. These are the necessary steps:

  • Create a file called `gulpfile.js at the root of your project.
  • Install gulp via npm if you haven't already: npm install gulp --save-dev
  • Install gulp-babel: npm install gulp-babel --save-dev

Now in the gulpfile, add something like the following:

At the top:

var gulp = require("gulp");

As a separate gulp task:

gulp.task("babel", function() {
  gulp.src(['aurelia/**/*.js', '!aurelia/_references.js'])
    .pipe(babel({
      "optional": ["runtime"],
      "stage": 0,
      'modules': 'system'
    }))
    .pipe(gulp.dest('wwwroot'));
});

This creates a gulp task called babel that

  • takes all javascript files under the aurelia folder (and subfolders)
  • except the _references.js file (which is a file used by Visual Studio 2015)
  • pipe those through the babel command, with certain options
  • copy those to the wwwroot folder

And more or less the same for your Aurelia templates. But these are just html files, so there is no transpiling necessary:

gulp.task('build-html', function() {
  gulp.src(['aurelia/**/*.html'])
    .pipe(gulp.dest('wwwroot'));
});

So now, instead of having ES2015 code in your wwwroot and having it transpiled on-the-fly, you get to write ES2015 code, but transpile it when building. This way, there is always ye olde javascript code in the wwwroot.