我遇到了同样的问题,经过几个小时的研究后,我意识到我问自己一个错误的问题,因为我想要做的不一定是使用 XHR 加载模板,而只是确保它们被缓存并存储在一个文件中。
我有一项繁重的任务,将我所有的 JADE 模板编译为 HTML,并将它们包装在一个大的 Angular 模块中,该模块作为一个名为 templates.js 的单独 JS 文件加载。 所有这些事情都是在后台自动完成的,所以在你花 10 分钟配置它之后,你实际上可以忘记猴子的工作,专注于代码/标记。
(为简洁起见,我将跳过 JADE 部分)
- 编辑html文件
- grunt-contrib-watch 任务:
- 抓住变化
- 在启用 $templateCache 的情况下生成角度模块
- 我的网站已重新加载(使用 liveReload)
这就是我使用 Grunt.js / JADE 和 html2js 解决问题的方式:
我的 index.jade 文件的头部
script(src='js/modernizr.js')
script(src='js/vendor.js')
script(src='js/templates.js')
script(src='js/app.js')
主应用模块的开始(这里使用 CoffeeScript)
'use strict'
# Declare app level module which depends on filters, and services
App = angular.module('app', [
'templates' // just include the module and forget it
'foo'
'bar']).config(...)
GruntFile.json(grunt.js 配置)
我需要删除大约 80% 的代码,只留下与模板相关的任务,将其视为草稿。
module.exports = (grunt)->
imports = grunt.file.readJSON 'app/imports.json'
grunt.initConfig
pkg: grunt.file.readJSON 'package.json'
watch:
options:
livereload: yes
templates:
files: 'app/**/*.jade'
tasks: ['buildTemplates']
jade:
default:
options:
client: no
wrap: no
basePath: 'app/'
pretty: yes
files:
'public/': ['app/**/*.jade']
html2js:
options:
module: 'templates'
base: 'public/'
main:
src: 'public/partials/**/*.html'
dest: 'public/js/templates.js'
connect:
server:
options:
port: 8081
base: 'public'
keepalive: yes
livereload:
options:
port: 8081
base: 'public'
# middleware: (connect, options)-> [lrSnippet, folderMount(connect, options.base)]
copy:
assets:
files:[
src:['**'], dest:'public/', cwd:'assets/', expand: yes
]
grunt.loadNpmTasks 'grunt-contrib-concat'
grunt.loadNpmTasks 'grunt-contrib-copy'
grunt.loadNpmTasks 'grunt-contrib-coffee'
grunt.loadNpmTasks 'grunt-contrib-clean'
grunt.loadNpmTasks 'grunt-contrib-connect'
grunt.loadNpmTasks 'grunt-contrib-compass'
grunt.loadNpmTasks 'grunt-contrib-watch'
grunt.loadNpmTasks 'grunt-contrib-livereload'
grunt.loadNpmTasks 'grunt-jade'
grunt.loadNpmTasks 'grunt-html2js'
grunt.registerTask 'buildTemplates', ['clean:templates', 'copy:assets', 'jade', 'html2js:main', 'livereload']
grunt.registerTask 'default', [ 'connect:livereload', 'watch']
结果
包含所有应用程序模板列表的单个 .js 文件,这些模板包含在与此类似的角度模块中:
angular.module("partials/directives/back-btn.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("partials/directives/back-btn.html",
"<a ng-href=\"{{href}}\" class=\"page-title-bar__back\"> <i class=\"icon-chevron-left\"> </i></a>");
}]);
链接
- grunt.js
- grunt html2js plugin