简体   繁体   中英

How should I compile html templates with Gulp in AngularJS project

I have following directory structure in my AngularJS application:

|-app
|--blog
|---BlogController.js
|---BlogService.js
|---BlogResource.js
|---states.js
|---templates
|----blog.html
|----blog-post.html
|----edit-blog-post.html
|--user
|---UserController.js
|---UserService.js
|---UserResource.js
|---states.js
|---templates
|----user-info.html
|----user-update.html
|-dist
|--js
|---all.js
|-templates
|--blog
|---blog.html
|---blog-post.html
|---edit-blog-post.html
|--user
|---user-info.html
|---user-update.html

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

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

Problem is in templateUrl property. When I build project actual place of all files changes and templateUrl doesn't point at html file. So templateUrl property must be changed in all.js 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(htmlmin())
        .pipe(angularTemplateCache('templates.js', {
            module: 'YOUR_ANGULAR_APP_NAME',
            root: ''
        }))
        .pipe(gulp.dest('dist'));
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM