Ionic2, Webpack and ECMAScript6 boilerplate

Today we had the chance to discover a Ionic2 presentation by @adamdbradley at AngularConnect London!

This presentation announces the alpha release of Ionic2 and shares the documentation on how to start building your own app with Ionic2.

As I got pretty excited I also created a boilerplate based on the cutePuppyPics starter kit by ionic team. My version is enhanced in many ways:

  1. removes gulp dependency (only webpack is needed and because you’re worth it 😉
  2. removes ionic-cli dependency (only cordova and webpack-dev-server are needed)
  3. removes dist files (only the sources are committed)

Running this boilerplate is as easy as running these two commands:

# Install dependencies
npm install

# Run the dev server
npm run devserver

Now open your browser on http://localhost:8080/ and enjoy Ionic2 🙂

Demo (3mb, can be pretty slow to load..)

Source available on Github : https://github.com/shprink/ionic2-webpack-ES6-boilerplate

WordPress Hybrid Client: v1.7.x now with native transitions

I am happy to announce the release of WPHC 1.7.x, this release adds native transitions by default to WPHC.

Under the hood WPHC uses https://github.com/shprink/ionic-native-transitions another plugin that I created to simplify native transitions usage on Ionic applications.

You can change the default options or disable native transitions using the configuration:

"cordova": {
    "nativeTransitions": {
        "enabled": true,
        "options": {
            "duration": 400,
            "slowdownfactor": 4,
            "iosdelay": 60,
            "androiddelay": 280,
            "winphonedelay": 200,
            "fixedPixelsTop": 0,
            "fixedPixelsBottom": 0
        }
    }
}

WordPress Hybrid Client (WPHC) is an Open Source project available on GitHub.

You can refer to the online documentation to properly build your applications. A Computer science background is required but the explanations should be clear enough.

1.7.0 ChangeLog

milestone

Native transitions for Ionic Framework made easier

I have heard about the Telerik’s native transition plugin for Cordova recently. To me this is not only a game changer in the hybrid industry, but in the entire mobile application industry.

Indeed with this improvement it will be really hard to tell what’s an hybrid application and what’s not. With the help of Ionic Framework, AngularJS and Cordova, hybrid applications are now sexiest than before, cheaper to produce and quicker to release. I started developing hybrid applications two years ago and the improvement made by Ionic, AngularJS, Cordova, Crosswalk are tremendous!

To help the Ionic community to use native transitions I created ionic-native-transitions a plugin available on github and npm where transitions are automatically added to your ionic application.

Just turn the plugin ON and enjoy native transitions 😉

native-transitions

Create a Mobile Application Using WordPress, Ionic, and AngularJS

Introduction

This tutorial is a post that I did for tutsplus.com. It will explain you step by step how to create a modern, hybrid, mobile application (iOS and Android) of your WordPress website using the latest technologies. We’ll be using Ionic Framework, ECMAScript 6, npm, webpack, and Apache Cordova.

http://code.tutsplus.com/tutorials/create-a-mobile-application-using-wordpress-ionic-and-angularjs–cms-24170

WordPress Hybrid Client: v1.6.x now supports iOS9

I am happy to announce the release of WPHC 1.6.x, this release supports iOS9, upgrade node and npm requirement and fixes some bugs.

As usual this release as been tested on OSX and Linux (Ubuntu) via docker https://github.com/shprink/wphc-dockerbox

You can refer to the online documentation to properly build your applications. A Computer science background is required but the explanations should be clear enough.

WordPress Hybrid Client (WPHC) is an Open Source project available on GitHub.

1.6.0 ChangeLog

milestone

WordPress Hybrid Client featured on sitepoint.com

This article on sitepoint.com is a tutorial on how to install WPHC step by step. It will help WPHC to reach new developers and hopefully grow the community.

Link to the tutorial: http://www.sitepoint.com/wordpress-hybrid-client-wordpress-powered-ios-android-apps/

Github project: https://github.com/shprink/wordpress-hybrid-client

WordPress Hybrid Client: v1.5.x

WordPress Hybrid Client: v1.5.x

I am happy to announce the release of WPHC 1.5.x, this release adds new features (comments, multi-level menu) but also focus on making the installation easier and lighter (12 dependencies were removed).

As usual this release as been tested on OSX and Linux (Ubuntu) via docker https://github.com/shprink/wphc-dockerbox

You can refer to the online documentation to properly build your applications. A Computer science background is required but the explanations should be clear enough.

WordPress Hybrid Client (WPHC) is an Open Source project available on GitHub.

1.5.0 ChangeLog

milestone

1.5.1 ChangeLog

milestone

Breaking Changes

  • “cache.views” and “cache.forward” configuration (within config.json) were move to “ionicConfig.views.maxCache” and “ionicConfig.views.forwardCache” respectively

1.5.2

Ultimate AngularJS and Ionic performance cheat sheet

As a lot of persons have asked me about how to improve AngularJS and/or Ionic performance. To avoid repeating myself on forums or on Slack I decided to create this ultimate cheat sheet list!

AngularJS

$watch

If you ever need to use $watch to listen to scope changes, you better use the right one. Indeed watched properties are examined on every call to $digest(), and therefore influence your application performance. There are three different ways to $watch scope properties:

$watch(watchExpression, listener, [objectEquality]);

Registers a listener callback to be executed whenever the watchExpression changes.

This is the basic $watch, it can be used like this:

$scope.$watch('watchExpression', function(newVal, oldVal){
    if(newVal){
        // watchExpression has changed.
    }
});

If watchExpression is an object that contains objects you can use objectEquality as true to deep watch watchExpression. While this is a super feature to have, it has a huge impact on your application performance:

$scope.$watch('watchExpression', function(newVal, oldVal){
    if(newVal){
        // watchExpression has changed.
    }
}, true);

My advice is to avoid using objectEquality when possible.

$watchGroup(watchExpressions, listener);

A variant of $watch() where it watches an array of watchExpressions. If any one expression in the collection changes the listener is executed.

Introduced in AngularJS 1.3, $watchGroup allows to watch several expressions at once.

$scope.$watchGroup([
    'watchExpression',
    'watchExpression2',
    'watchExpression3'
], function(newVals, oldVals) {
    if (newVals[0]) {
        // watchExpression has changed.
    }
    if (newVals[1]) {
        // watchExpression2 has changed.
    }
    if (newVals[2]) {
        // watchExpression3 has changed.
    }
});

While $watchGroup might not improve your application performance compare to $watch, it has the advantage to be more synthetic when watching several scope expressions.

$watchCollection(obj, listener);

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties). If a change is detected, the listener callback is fired.

$watchCollection can be considered in between the $watch and the $watch with objectEquality (deep watch). It also works comparing object references but with the advantage to also shallow watches the properties of your object.

For instance adding an element to an array that you watch will not trigger the normal $watch but trigger the $watch with objectEquality and the $watchCollection.

I recommend using the $watchCollection over the $watch with objectEquality when necessary. It is less expensive and therefore better for performance.

To go further on $watch and $watchCollection differences I recommend this article by Ben Nadel: http://www.bennadel.com/blog/2566-scope-watch-vs-watchcollection-in-angularjs.htm


One-time binding

An expression that starts with :: is considered a one-time expression. One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value.

One-time binding :: was also introduced in Angular 1.3. It has a real impact on your application performance.

Basically using One-time binding :: on expression will remove it from the $watchers list when populated. It means that the expression will not be able to update even if the data changes.

For instance displaying the user first name on an application is unlikely to be updates, therefore is a good candidate for One-time binding :::

{{::user.first_name}}

My advice is to go through all your applications views and think about what could or could not be updated and use One-time binding :: accordingly. It will be a huge relief for the digest cycle!


Track by

track by is used to avoid useless DOM manipulation when using ng-repeat. Indeed if the digest cycle finds that at least one element of your collection has changed, ng-repeat will re-render all elements. DOM manipulation always has effects on the application performance, the less you have the better. To avoid re-rendering the complete collection and only change the elements that need to be changed use track by with a unique identifier.

Change your code from that:

ng-repeat="user in users"

to:

ng-repeat="user in users track by user.id" (if users have a unique id) or ng-repeat="user in users track by $index" if they don’t. $index is added by ng-repeat to each elements of your collection.


Logs

When using AngularJS do not use console.log, having them on a production application can slow down performances (see this jsperf). Some tools such as gulp-strip-debug automatically removes them from your code but my advice is not use console.log at all. AngularJS has a built in service that just does that: $log. It can be switched off using the $logProvider provider:

angular.module('yourModule').config(function($logProvider) {
    if (/* test if in production */) {
        $logProvider.debugEnabled(false);
    }
});

The $log service has several log levels .info .debug and .error.


Debug

AngularJS by default adds scope references to the DOM for tools such as angularjs-batarang to work. This has an impact on your application performance.

It can be disabled using the $compileProvider provider:

angular.module('yourModule').config(function($compileProvider) {
    if (/* test if in production */) {
        $compileProvider.debugInfoEnabled(false);
    }
});

Loops

Depending on the browser you use, JavaScript performance can be different. I set up 9 loop tests that go through an array of one hundred elements:

var arr = new Array(100);

# while loop
var i = 0;
while (i < arr.length) {
  arr[i];
  i++;
};

# cached while loop
var i = 0,
  len = arr.length;
while (i < len) {
  arr[i];
  i++;
};

# Reverse while loop
var i = arr.length;
while (i--) {
  arr[i];
};

# for loop
for (var i = 0; i < arr.length; ++i) {
  arr[i];
};

# cached for loop
var i = 0,
  len = arr.length
for (; i < len; ++i) {
  arr[i];
};

# Reverse for loop
for (var i = arr.length; i--;) {
  arr[i];
};

# Angular foreach
angular.forEach(arr, function(value, i) {
  arr[i];
});

# Native foreach
arr.forEach(function(value, i) {
  arr[i];
});

# Lodash foreach
_.forEach(arr, function(value, i) {
  arr[i];
});

At the end we can compare the results. What is the most performant way to iterate on an Array? Well apparently the “cached for loop” tend to be the best alternative across browsers. Native and Angular foreach are just 13 times less efficient than the cached loop…

The “cached for loop” does not re-evaluate the arr.length at every iteration, that’s why is it faster than the normal “for loop”.

It is also interesting to notice that lodash performance is four times better than angular foreach. If you do not like to use native for loops I recommend using lodash (I love this lib).


Animations

According to Ben Nadel’s blog post: Enable Animations Explicitly For A Performance Boost In AngularJS it is possible to force ngAnimate to only target elements that have a specific class name instead of checking all elements seeking for elements that could animate.

angular.module('yourModule').config(function($animateProvider) {
    $animateProvider.classNameFilter( /banimatedb/ );
});

I personally have not tested this approach but according to Ben Nadel’s numbers it could make a significant performance enhancement.


Ionic

Native scrolling

Native scrolling was released in May 2015 with Ionic 1.0. Before that Ionic relied on the JavaScript scrolling which was created to have proper events for features such as “Pull To Refresh”, Infinite Scrolling, List Reordering, or Collection Repeat. Browsers evolved to handle native scrolling events but mostly on Android, iOS in Cordova still doesn’t have completely native scroll events.

Native scrolling can be enabled using overflow-scroll=”true” on your ion-content or using the $ionicConfigProvider provider:

angular.module('yourModule').config(function($ionicConfigProvider) {
    $ionicConfigProvider.scrolling.jsScrolling(false);
});

My advice is to always enable it, once you have tested it you cannot live without it!

More information


Collection repeat

The collection-repeat directive is a directive that allows you to render lists with thousands of items and experience little to no performance penalty. It renders into the DOM only as many items as are currently visible.

Collection repeat is good for performance, but not on every cases. Indeed Collection repeat must $watch every item and item properties of your collection (you cannot use the One-time binding or track by with it). Depending on the data you want to display the number of $watchers can slow down your application.

<ion-content>
  <ion-item collection-repeat="item in items">
    {{item}}
  </ion-item>
</ion-content>

Another downside is that you cannot use native scrolling with a collection repeat.

More information


Infinite Scroll

The<ion-infinite-scroll> directive allows you to call a function whenever the user gets to the bottom of the page or near the bottom of the page. It has the advantage to only load the right amount of data that the user needs.

<ion-content ng-controller="MyController">
  <ion-list>
  ....
  ....
  </ion-list>

  <ion-infinite-scroll
    on-infinite="loadMore()"
    distance="1%">
  </ion-infinite-scroll>
</ion-content>

From my experience in a lot of cases using the infinite scroll combined with the One-time binding, track by and the Native scrolling is way better in terms of performance than a collection repeat.

More information


View cache

The view cache is one of Ionic’s killer feature. If enabled it keeps views in the DOM cache with their scope, current state, and scroll position. When navigating you never lose your input or scroll position so you can go back in history without the fear of losing data.

What about performance then? Well when a page is cached its scope is disconnected from the $watch cycle and reconnected when used again. It means that the number of $watchers are the same as if you do not use the view cache. However keeping views in the DOM and saving theirs states in memory have an impact on the application performance. My advice is to use this feature (it is a MUST have) but to cache only a reasonable amount of pages using the $ionicConfigProvider provider:

angular.module('yourModule').config(function($ionicConfigProvider) {
    $ionicConfigProvider.views.maxCache(5);
});

By default, Ionic will cache a maximum of 10 views, and not only can this be configured, but you can also explicitly state which views should and should not be cached using the <ion-view cache-view="false"> directive or the UI router $stateProvider provider.

$stateProvider.state('myState', {
   cache: false,
   url : '/myUrl',
   templateUrl : 'my-template.html'
});

More information


Events

When using AngularJS it is considered a good practice to load your data using the $viewContentLoaded event in controllers. When using Ionic SDK, this event is not usable, instead we have access to more specific events. The Ionic view cache comes with 8 new events, for instance “$ionicView.loaded” is triggered once per view being created and added to the DOM while the “$ionicView.enter” event will fire, whether it was the first load or a cached view.

Using the right event to load your data can improve the usability of the application. Indeed the less HTTP requests you send the better for the usability.

Here is the complete list of events that you can use with Ionic:

$scope.$on('$ionicView.loaded', function(){});
$scope.$on('$ionicView.enter', function(){});
$scope.$on('$ionicView.leave', function(){});
$scope.$on('$ionicView.beforeEnter', function(){});
$scope.$on('$ionicView.beforeLeave', function(){});
$scope.$on('$ionicView.afterEnter', function(){});
$scope.$on('$ionicView.afterLeave', function(){});
$scope.$on('$ionicView.unloaded', function(){});

More information


Native transitions

It is now possible to use native transitions within Ionic applications. I created ionic-native-transitions, a plugin that helps you configuring Telerik’s native transition Cordova plugin.

More information


Cordova

Crosswalk

I highly recommend using Crosswalk. Basically it embedded the latest chromium into the app (adding around 20Mb per apk: ARM and X86) so you have the same experience on every android version/device.

Installing it is as easy as that:

cordova plugin add cordova-plugin-crosswalk-webview@1.2.0

Try it out, for me Crosswalk has been a game changer in the hybrid industry, it makes applications smoother.


That’s all I could come up with on top of my head, if I missed things please let me know by commenting.

Modular AngularJS and Ionic architecture: a first step towards AngularJS 2

This post describes the architecture that you can use RIGHT NOW on your AngularJS 1.x or Ionic applications and that will be compatible with AngularJS 2. When the time comes and according to this article: Angular 1 and 2 running together, you will be able to migrate easily your application, module by module.

Forget what you know

A large majority of the Ionic, AngularJS 1.x projects are using Bower, Gulp and a folder-by-type architecture. If you want to build large scale applications with several developers, you will definitely have problems if you follow that kind of architecture.

AngularJS is often used to create prototypes and MVP really quickly so why bother? Well, we all know what happen to prototypes and MVPs that somehow work… they go directly into production. If you have reached that point, it is not too late to restructure your code and think about it before your application turns into FrankenstApp!


Bower

Here are few reasons not to use Bower:

  1. It does not support CommonJS out of the box.
  2. Using npm and Bower at the same time is a non sense (they both fulfill the same need).
  3. npm has become the most popular package manager for JavaScript.
  4. Requires closures to avoid scope leaking.

If you want to know more reasons I recommend you to read this article: Why my team uses npm instead of bower

What is CommonJS?

The CommonJS group defined a module format to solve JavaScript scope issues by making sure each module is executed in its own namespace.

CommonJS handle modules outside the browser and works great with ECMAScript 5 or 6.

// Import with ECMAScript 5
var angular = require('angular');

// Export with ECMAScript 5
module.exports = function(){}

// Import with ECMAScript 6
import angular from 'angular';

// Export with ECMAScript 6
export default function(){}

Gulp

Few reasons not to use Gulp:

  1. Compiling, concatenating and minifying your application require to install a lot of dependencies (gulp-concat, gulp-minify-css, express, livereload etc.).
  2. Basic needs (web server, livereload, concat etc) require to create many scripts that YOU will need to maintain yourself.

In 2015 it should not be that complicated to fulfill your application’s basic needs. The solution is to use Webpack.


Folder-by-type structure

The folder-by-type structure is basically grouping JavaScript files by types (controllers, configs, views, directives etc.) as followed:

app/
    app.js
    controllers/
        aaa.js
        bbb.js
        ccc.js
    directives/
        ddd.directive.js
        eee.directive.js
        fff.directive.js
    services/
        xxx.js
        yyy.js
        zzz.js
    views/
        aaa.html
        bbb.html
        ccc.html
        ddd.directive.html
        eee.directive.html
        fff.directive.html

This folder architecture is a terrible idea for large scale applications. I have experienced it before and it is not a good memory, especially if you are several developers to work at the same time. Here are some reasons not to use it:

  1. The number of files in your folders can become really large.
  2. Finding all the files you need to modify for a specific feature can be tricky.
  3. Working on a feature will lead to open many folders.

If you do not trust me, at least trust John Papa’s styleguide 🙂

A better solution is to Create components/modules with a Folders-by-Feature structure.


Use Webpack

Webpack is a module bundler, it takes modules with dependencies and generates static assets.

Webpack and Webpack-dev-server easily replace Gulp for basic application needs (web server, livereload, concatenation, minification, compliling JS or Sass etc.). Instead of having to maintain several Gulp scripts, what you only need is a configuration file webpack.config.js… that’s ALL!

For instance having an autoprefixed CSS injected into your application from several Sass files is as simple as that with Webpack:

{
    test: /.scss$/,
    loader: "style!css!autoprefixer!sass"
}

No need to show you the equivalent using Gulp or Grunt, I think you got my point! If you want to go further with Webpack you can read this article I created some time ago: Introduction to Webpack with practical examples


Create components/modules

The solution to large scale applications is to create loosely coupled modules. I have been doing AngularJS applications for a long time now and after a lot of experimenting I have settled to the following architecture:

  • Every file that can be edited, live in the src/ or /lib folder.
  • Every AngularJS module needs a proper folder.
  • Every module file *.module.js must define a unique namespace (and must be the only place where this namespace appears).
  • Every module file *.module.js must declare all its dependencies (even if dependencies are already injected in the app).
  • Every module file *.module.js must declare all its configs, controllers, services, filters etc.
  • Every config, controller, service, filter etc. must export a function or a Class.
  • If a module needs some specific style, the .scss file must live within the module as well.

All of this is very powerful, it assures you to have modules that can be shared by several applications without getting any error (except for missing dependencies).

Here an example of a home module structure:

lib/
    index.js
    home/
        home.module.js
        home.config.js
        home.service.js
        home.controller.js
        home.html
        home.scss

Now here is the home.module.js file using ECMAScript 6:

import modConfig from './home.config';
import modController from './home.controller';

let mod = angular.module('prototype.home', [
    'ionic',
    'ui.router'
]);

mod.config(modConfig);
mod.controller('HomeController', modController);

export default mod = mod.name

Use Folders-by-Feature structure

Reasons to use Folders-by-Feature structure:

  1. The number of files in your folders are limited to few.
  2. Finding all the files you need to modify for a specific feature is easy (they are in the same folder!).
  3. You can work independently on a feature.
  4. Knowing what the module represents is easy (the folder name is sufficient).
lib/
    index.js
    home/
        home.module.js
        home.config.js
        home.service.js
        home.controller.js
        home.html
        home.scss
    parameters/
        parameters.module.js
        parameters.config.js
        parameters.service.js
        parameters.controller.js
        parameters.html
        parameters.scss

Recommended boilerplates

If you are ready to start making some changes in your application with the architecture I suggested in this post you can clone those repositories, they are a good start:

  1. [Angular Material]: shprink/angular1.4-ES6-material-webpack-boilerplate. A simple AngularJS 1.4 boilerplate using ES6, material design and Webpack.
  2. [Ionic]: shprink/ios-android-wordpress-ionic-webpack-ES6. Repo created for the TutsPlus article: Creating iOS/Android mobile applications for WordPress using Ionic SDK, Webpack, ES6 and WP-API.

WordPress Hybrid Client: v1.4.0 released

WordPress Hybrid Client (WPHC) is an Open Source project available on GitHub.

You can refer to the online documentation to properly build your applications. A Computer science background is required but the explanations should be clear enough.

v1.4.0 ChangeLog

milestone

Breaking Changes

The menu configuration is now located in menu.list within the config.json file. You will need to update it accordingly to the following changes:

  1. menu.settings changed to settings in the config.json file
  2. menu.wordpress is removed from config.json file
  3. menu.social is removed from config.json file
  4. menu.list is the new menu declaration object