Customizing Ionic Generators

I recently was having a conversation with @leifwells about some Ionic development, and he mentioned that he was having to add in some Google analytics code on each of his existing pages. This led to talking about being able to modify the templates the Ionic generate command uses to include custom items. For example, this might be some standard code like adding in the shell code for GA, or it might be needing to add in legal notices required by corporate. After some failed attempts wandering through various repos on GitHub, I ask the Ionic team where they were kept. I had thought they would be in the CLI or maybe in the app-scripts. Instead, they are in the ionic-angular package. Specifically, the templates are located here: node_modules/ionic-angular/templates/.

Here is what the ts.tmpl file for a page contains:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

/**
 * Generated class for the $CLASSNAME page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
 selector: 'page-$FILENAME',
 templateUrl: '$FILENAME.html',
})
export class $CLASSNAME {

 constructor(public navCtrl: NavController, public navParams: NavParams) {
 }

 ionViewDidLoad() {
   console.log('ionViewDidLoad $CLASSNAME');
 }

}

Now, if you have been developing with Ionic for a while, you probably delete the comment block at the top of the file, as well as the console.log call within the ionViewDidLoad function. By editing the actual template, we can save ourselves those steps.

Note, the edits you make here can be overwritten by running npm install, and they are specific to this specific Ionic App. You will need to keep your template changes in another directory and apply them again to each new project.

Now, that you know where these templates are located, you can go in and adjustment to improve your workflow. Happy coding!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.