We have been dabbling with JSPM and AngularJS together to make new sites.

This dabbling uncovered some wrinkles you’ll likely encounter during this transition phase, and we published two projects to github with our solutions in March 2015.

ES6 + AngularJS + Twbs Starter project

This project is a boilerplate to start out making your new web project (single page app or not) without having to remember or re-figure out how to get ES6 and AngularJS 1.x to play well together.

This project is pre-configured so you can hit the ground running using the following setup:

Hiram ES6 Logger

This is the AngularJS $logProvider pulled out into a standalone ES6 module.

Why?

If you are refactoring your AngularJS code into ES6 classes and modules, it is very likely you are running into to the overlap of AngularJS Dependency Injection and ES6 imports.

Example of mixing ES6 with AngularJS DI

class MyClass{
    static factory($log, dep1, dep2, ...){
        return new MyClass($log, dep1, dep2, ...);
    }

    constructor($log, dep1, dep2, ...){
        this.$log = $log;
        this.dep1 = dep1;
        this.dep2 = dep2;
        ...
    }

    doSomethingAwesome(){
        this.$log.debug(`Everything is better when you're part of a team!`);
        ...
    }

}

MyClass.factory.$inject = ['$log', 'dep1', 'dep2'];

export default MyClass;

Notice how ‘$log’ has to be defined and passed through three times, once at $inject, once at the factory, and once at the constructor. This is less than elegant, but it’s understandable given the transition period of ES6 and 1.X AngularJS.

However, as a consequence the calls to $log have to be prefixed with ‘this’ as in this.$log … that is way too much work for what should be ‘easy.’

Why should logging be easy? Because easy things are done often, and verbose logging makes for maintainable code.

Reworked example using this logging module

import $log from 'hlog'

class MyClass{
    static factory(dep1, dep2, ...){
        return new MyClass(dep1, dep2, ...);
    }

    constructor(dep1, dep2, ...){
        this.dep1 = dep1;
        this.dep2 = dep2;
        ...
    }

    doSomethingAwesome(){
        $log.debug("Everything is better when you're part of a team!");
        ...
    }

    MyClass.factory.$inject = ['dep1', 'dep2'];

    $log.debug('MyClass is now available');

    export default MyClass;
}

Notice how $log is available throughout the file, both within the class and also without it. Also, notice how this.$log disappeared.

What’s more, $log has no dependency on AngularJS so you can use this logging anywhere and everywhere.