我应该如何在 AngularJS 项目中使用 Gulp 编译 html 模板

Nik*_*kov 3 angularjs angular-ui-router gulp

我的 AngularJS 应用程序中有以下目录结构:

|-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
Run Code Online (Sandbox Code Playgroud)

app文件夹用于开发,dist文件夹用于生产。我使用 Gulp 来构建项目。state.js文件包含 ui.router 状态配置。这是此文件的示例:

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

问题出在templateUrl财产上。当我构建项目时,所有文件的实际位置都会发生变化并且templateUrl不指向 html 文件。因此templateUrl必须在all.js文件中更改属性。我怎样才能用 Gulp 做到这一点?

Mad*_*one 5

在我看来,最好的方法是使用 Angular 的模板缓存。有一个名为gulp-angular-templatecache的 gulp 插件可以帮助生成此输出。

例如,假设您的内容blog/templates/blog-post.html是:

<h2>{{ :: blog.title }}</h2>
<p>{{ :: blog.content }}</p>
Run Code Online (Sandbox Code Playgroud)

你可以有一个这样的吞咽任务:

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'));
});
Run Code Online (Sandbox Code Playgroud)

这将创建一个dist/js/templates.js包含以下内容的文件:

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>');}]);
Run Code Online (Sandbox Code Playgroud)

您所有的模板来自app/该文件,任何调用templateUrl都将能够找到正确的模板。

此解决方案解决了templateUrl链接断开的问题,同时还减少了客户端浏览器必须发出的请求数量。你也可以更进一步,结合templates.js你的,dist/js/all.js这样只有一个 JavaScript 文件。