Nikita Gorshkov Nikita Gorshkov - 2 months ago 10x
AngularJS Question

How should I compile html templates with Gulp in AngularJS project

I have following directory structure in my AngularJS application:


folder is for develompment,
folder is for production. I use Gulp for building project.
files contain ui.router states configutation. Here is example of this file:

app.config(['$stateProvider', function ($stateProvider) {
.state('blog-post', {
url: '/blog-posts/:id',
templateUrl: 'blog/templates/blog-post.html',
controller: BlogPostController

Problem is in
property. When I build project actual place of all files changes and
doesn't point at html file. So
property must be changed in
file. How can I accomplish this with Gulp?


The best way to do this, in my opinion, is to use Angular's template cache. There is a gulp plugin called gulp-angular-templatecache that can help generate this output.

For example, say the contents of your blog/templates/blog-post.html are:

<h2>{{ :: blog.title }}</h2>
<p>{{ :: blog.content }}</p>

You could have a gulp task like this:

var gulp = require('gulp');
var htmlmin = require('gulp-htmlmin');
var angularTemplateCache = require('gulp-angular-templatecache');

gulp.task('templates', function() {
    return gulp.src('app/**/*.html')
        .pipe(angularTemplateCache('templates.js', {
            module: 'YOUR_ANGULAR_APP_NAME',
            root: ''

That will create a file dist/js/templates.js with this content:

angular.module('YOUR_ANGULAR_APP_NAME').run(['$templateCache', function($templateCache) {$templateCache.put('blog/templates/blog-post.html','<h2>{{ :: blog.title }}</h2>\n<p>{{ :: blog.content }}</p>');}]);

All your templates from app/ will end up that file, and any call to templateUrl will be able to find the correct template.

This solution solves the problem of your broken templateUrl links, and also it reduces the number of requests the client's browser has to make. You could also take that a step further and combine templates.js with your dist/js/all.js so that there is only one JavaScript file.