Using ES6 modules in an ES5 RequireJS project

February 12, 2015

I want to start a new library in Javascript ES6 but also use it within our production ES5 code which uses RequireJS. I created a quick spike to see how straight forward this would be. Turns out it is very easy thanks to 6to5.

My goal was to create a simple RequireJS module which requires the ES6 transpiled module as a dependency.

Writing the modules

The ES6 module uses some of the new ES6 language features, class, static, const and the simpler method definition. The module will export a class called Hello with a static function render() to add an H1 to the page. This will the be transpiled to a file named say-hello-es6.js.

export class Hello {
    static render() {
        const h1 = document.createElement('h1');
        h1.textContent = "Hello I'm ES6.";

        document.body.appendChild(h1);
    }
}

The ES5 RequireJS module imports the ES6 transpiled module and calls the static function from the exported class via helloES6Module.Hello.render().

define(['say-hello-es6'], function(helloES6Module) {
    var h1 = document.createElement('h1');
    h1.textContent = "Hello I'm RequireJS.";

    document.body.appendChild(h1);

    helloES6Module.Hello.render();
});

Integrating into a Grunt build process

Our project uses Grunt to build the codebase and again it was easy to integrate the transpiling of ES6 code into the build process.

The Grunt plugin grunt-6to5 makes it as simple as adding the following to the grunt.initConfig.

'6to5': {
    options: {
        sourceMap: true,
        modules: 'amd'
    },
    dist: {
        files: {
            'dist/say-hello-es6.js': 'src/es6/say-hello.js'
        }
    }
}

To transpile the ES6 module into an AMD module suitable for RequireJS set the modules option to 'amd'.

Remaining unknowns

We use Mocha, Sinon and Chai for testing. Our unit tests are run either on the command line with node via PhantomJS or directly in a browser.

Some issues I think we're going to have to work around include:

  • having to pre-transpile the tests before running them, currently they point directly to the source
  • how will we adjust to debugging in the browser via sourcemaps

More information

For further information on ES6 modules and the 6to5 transpiler see the following pages: