Use ES6 JavaScript today using System.JS, Babel, JSPM and Gulp

Developers are always looking forward to future JavaScript features, including structured classes shorthand coding and helpers. However many of these features are not standardised and/or compatible with all modern browsers, and the ones that are agreed are not supported by legacy browsers.

There are many tools which allow you as a developer to write using future features, and the tools will convert your code to support other browsers. Today we are going to look at how they work and an example workflow which you can use now on live projects.


First off lets create a JavaScript file with some ES6 syntax code. Lets use the new default parameters syntax (which is not yet supported by many browsers) called src/all.js

import multiply from './multiply';
document.getElementById('list').innerHTML = multiply(5);

And create a file src/multiply.js
var multiply = (a, b = 2) => {
    return a * b;
}
export default multiply;

And we will also create a simple html page loading the javascript src/index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>ES6 Modules</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
</head>
<body>
    <div id="list"></div>
    <script src="all.js"></script>
</body>
</html>

When this is loaded within most browsers it will error "Unexpected token import", as the browser does not understand the import syntax yet. So how can we add support for ES6?

The answer is to add a JavaScript compiler called Babel.js which will transform your ES6 code into ES5. There are different ways to run Babel on your code. You could use a command line on your script, or the online compiler, but we are going to use a module loader which will compile the files dynamically inside your browser. Much easier!

Firstly we will add the System.js module loader, which will load your all.js file and then run Babel.js compiler on it, and run the result for you.

1) Ensure you have started a new npm project and have jspm installed:
npm install jspm --save-dev

2) Next you need to initialise jspm in the folder root:
jspm init

3) Fill out the questions it asks using the options below:
Package.json file does not exist, create it? [yes]: yes
Would you like jspm to prefix the jspm package.json properties under jspm? [yes]: yes
Enter server baseURL (public folder path) [./]: ../
Enter jspm packages folder [.\jspm_packages]:
Enter config file path [.\config.js]:
Configuration file config.js doesn't exist, create it? [yes]: yes
Enter client baseURL (public folder URL) [/]: ../
Do you wish to use a transpiler? [yes]: yes
Which ES6 transpiler would you like to use, Babel, TypeScript or Traceur? [babel]: babel

4) JSPM has automatically installed the System.js module loader for you. So update your index.html to load it into the page:
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>ES6 Modules</title>
    <meta name="description" content="" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
</head>
<body>
    <div id="list"></div>
    <script src="../jspm_packages/system.js"></script>
    <script src="../config.js"></script>
    <script>
        System.import('./all.js');
    </script>
</body>
</html>

Now when you run this page in your browser you should see the Number outputted! Great stuff, so what next? You can use this for development, but every time you change a file you need to reload the page and all of the System.js polyfill code which takes time. Lets add an automated task to watch our javascript files and reload them in the page.

1) Add gulp-connect package using the command:
npm install gulp --save-dev
npm install gulp-connect --save-dev

2) Create a gulpfile.js containing the following code:
var connect = require('gulp-connect'),
    gulp = require('gulp');

gulp.task('connect', function () {
    return connect.server({
        root: '',
        livereload: true,
        port: 8181
    });
});

gulp.task('watch', function() {
    gulp.watch(['src/**/*.js'], function(event) {
        gulp.src(event.path)
            .pipe(connect.reload());
    });
});

gulp.task('default', ['connect', 'watch']);

3) Now run the command in your terminal:
gulp

4) Go to http://localhost:8181/ in your browser and view the Network requests to see a livereload script being loaded. Try changing your js file and saving it to see the automatic reload!

To create the ES5 version for deployment you will need to:

1) First install the gulp-jspm library to ease use with gulp streams:
npm install gulp-jspm --save-dev

2) Next include it in your gulp file along with your new task:
var jspm = require('gulp-jspm');
gulp.task('compile', function () {
    return gulp.src('src/all.js')
        .pipe(jspm({selfExecutingBundle: true}))
        .pipe(gulp.dest('src'));
});
3) Run the gulp task and view the new all.bundle.js file created:
gulp compile

You can view a more developed version of this structure here including other tools such as SASS and modular components:
https://github.com/kmturley/es6-modules

No comments:

Post a Comment