本文主要讲如何用Grunt打包AngularJS的模板HTML。
一 说明
AngularJS中使用单独HTML模板文件的地方非常多,例如:自定义指令、ng-include、templateUrl等。通常这些文件都是独立的html文件,AngularJS中使用这些文件都是通过文件路径地址引用的。
当用Grunt打包压缩整个项目时,如何处理这些html模板文件呢?本文讲的grunt-angular-templates插件可以解决该问题。
grunt-angular-templates插件的基本原理:
该插件实际使用的是AngularJS的$templateCache服务,将这些模板文件都缓存起来,当自定义指令、ng-include等需要对应的html文件时,AngularJS首先会去$templateCache中找对应的文件,如果找到了就不在发送XHR请求。
使用$templateCache缓存模板可以减少XHR请求数,并实现html文件打包。
同时,在AngularJS内部,第一次请求到模板HTML后,都会被缓存到 $templateCache 服务中,这样就确保一个文件只被请求一次。
下边是使用$templateCache缓存html模板的方法:
1 angular.module('app').run(["$templateCache", function($templateCache) { 2 $templateCache.put("home.html", 3 // contents for home.html ... 4 ); 5 ... 6 $templateCache.put("src/app/templates/button.html", 7 // contents for button.html 8 ); 9 }]);
二 安装
$ npm install grunt-angular-templates --save-dev
三 加载任务
grunt.loadNpmTasks('grunt-angular-templates');
四 配置
五 实战
六 源码下载地址
参考资料&内容来源
grunt官网:https://www.npmjs.com/package/grunt-angular-templates
博客园:https://www.cnblogs.com/ms-grf/p/6874256.html