Angular and Gulp

Streamlining Angular code is sublime. We can streamline the process of optimizing Angular apps for dependency injections, template caching, and common JavaScript optimizations such as minification, all in preparation for production using build automation tools like Gulp.js. Gulp is based on streams follows the mantra of “code over configuration’.

My new course JavaScript Build Automation with Gulp.js was just released on Pluralsight. You can learn how to make your JavaScript do tricks and develop more efficiently, using Gulp in this course. In this course I take you from learning what Gulp does, how to install it on both Windows and a Mac, to building an entire build pipeline step by step. I spend a lot of time explaining why each step exists and what the value of the Gulp tasks are.

Angular Template Caching

One example of how to streamline your Angular app is to let Gulp do the work of taking your HTML templates and pushing them into the Angular $templateCache service. This means that the templates for your directives and views, for example, will not need to make an extra HTTP call to get each template.

Let’s explore how this works in Angular first. When a directive executes it will need its template. Angular first checks the $templateCache to see if the template exists in there. The $templateCache is a dictionary of entries, keyed by the url of each template. If the template exists in the cache, it will provide it to the directive. If it does not exist, it will go to the url over HTTP and retrieved the template, stick it in the cache, and provide it to the directive. We can save a lot of HTTP traffic for directives if we stuff these templates into the $templateCache in advance. This is effectively priming the cache.

Where does Gulp step in? It is ideal for automating tasks like this as it can go through all of our code and determine what to stuff into the cache, generate a file that contains the Angular code to stuff the $templateCache, and customize it to add it to an existing module or create a new stand alone module. Gulp uses the gulp-angular-templatecache plugin to do the work here.

Here is a code snippet from the course:

// Gulp task for creating template cache
gulp.task('templatecache', function() {
    log('Creating an AngularJS $templateCache');

    return gulp
        .src(config.htmltemplates)
        .pipe($.minifyHtml({empty: true}))
        .pipe($.angularTemplatecache(
            config.templateCache.file,
            config.templateCache.options
        ))
        .pipe(gulp.dest(config.temp));
});

First I provide the source files to gulp, which are the html templates in my project. Then I minify the HTML (leaving empty tags alone in case they are needed). Why minify the HTML? Why not? Saving any bytes can be helpful.

Next the template cache runs through the code an creates a file named templates.js in a temp folder. My index.html looks for the templates in that folder. Later I will optimize all of the JavaScript, but for now this does nicely.

I use config variable settings for all of my file paths. I find this makes it much easier to modify the file for multiple projects.

// Path settings for Gulp
var clientApp = './src/client/app/';
var config = {
    htmltemplates: clientApp + '**/*.html',
    templateCache: {
        file: 'templates.js',
        options: {
            module: 'app.core',
            root: 'app/',
            standAlone: false
        }
    },
    temp: './.tmp/'
};

here is an example of what the $templateCache looks like (with … replacing the HTML and some formatting I added for readability):

angular
    .module("app.core")
    .run(["$templateCache", function($templateCache) {
        $templateCache.put("app/dashboard/dashboard.html","<section> ... </section>");
        $templateCache.put("app/layout/ht-top-nav.html","<nav> ... </nav>");
        $templateCache.put("app/widgets/widget-header.html","<div> ... </div>");
    }]);

This is just one example showing how you can add value to your development efforts using Gulp!

What Else is in the Course

Here is a brief outline of the course:

  1. Requirements
  2. The Value of JavaScript Task Runners (Are You Working Too Hard?)
  3. The Gulp API
  4. Getting Started with Gulp
  5. Code Analysis and Separating Tasks from Config
  6. CSS / Less Tasks and Error Handling
  7. Build Task with Injection
  8. Serving a Dev Build
  9. Browser-Sync
  10. Images and Fonts and Cleaning
  11. Angular Template Caching
  12. Creating and Serving a Production Build
  13. Minification and Filters
  14. Angular Dependency Injections
  15. Static Asset Revisions and Version Bumping
  16. Testing in Terminal
  17. Testing in a Browser
  18. First Look at Gulp 4