Grunt学习笔记【8】---- grunt-angular-templates插件详解
本文主要讲如何用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模板的方法:
angular.module('app').run(["$templateCache", function($templateCache) {
$templateCache.put("home.html",
// contents for home.html ...
);
...
$templateCache.put("src/app/templates/button.html",
// contents for button.html
);
}]);
二 安装
$ npm install grunt-angular-templates --save-dev
三 加载任务
grunt.loadNpmTasks('grunt-angular-templates');
四 配置
这里主要讲作者用到的几个常用配置:
4.1 src
要打包的模板文件路径。例如:'src/**/*.html'。
4.2 dest
输出打包好的文件地址。例如:'dist/tmp.js'。
4.3 options
各种设置都在options中,常用的有下边几个:
1)htmlmin
最小化html大小。设置了该项会去掉html的空格和换行等,可以减少压缩后文件大小。
官网推荐的设置如下:
htmlmin :{
collapseBooleanAttributes :true ,
collapseWhitespace :是的,
removeAttributeQuotes :true ,
removeComments :true ,// 仅当您不使用comment指令时!
removeEmptyAttributes :true ,
removeRedundantAttributes :true ,
removeScriptTypeAttributes :true ,
removeStyleLinkTypeAttributes :true
}
2)standalone
设置是否创建新的AngularJS模块,还是使用一个现有的AngularJS模块。
设置为true时,将创建一个新的AngularJS模块,类似angular.module('app', []);
设置为false时,将使用已有的模块,类似angular.module('app')。
说明:该模块用于提供$templateCache进行模板缓存;模块名来自于下边的module属性。
3)module
设置创建的Angular模块名字,默认值为target,即Grunt配置项中ngtemplates的下一级属性名。
注意:
module和上边的standalone接口配合起来使用,如果是新创建的模块,必须在AngularJS启动模块中将该模块依赖进来,否则会导致找不到模板报错;如果是使用已有模块,就必须确保在加载打包后的html模板js之前已经定义了对应的模块,否则也会报错。
4)prefix
将模块存入到$templateCache时,对key添加的前缀。
注意1:如果设置了该属性,就要确保自定义指令、ng-include等中设置的模板地址也带有该前缀。
注意2:最终存入的存入到$templateCache的key是prefix+src后的结果,这里的src就是上边接口。
5)bootstrap(module, script)
该回调函数用于自定义模板缓存创建。
如果不定义该函数,插件会自己创建或者获取AngularJS模块,并通过run方法将所有html模板缓存到$templateCache中。
如果定义了该函数,则必须自己实现模板缓存到$templateCache,并将对应的js代码返回。最终会将返回的结果合并到输出文件中。
使用场景:将模板注册成AMD或者commonJS模块。例如:在requireJS构建的项目中。
参数说明:
module:AngularJS模块。
script:$templateCache.put()方法调用的js代码,如下:
$templateCache.put('/aa/src/button.html',
"<button type=button>{{text}}</button>"
);
五 实战
下边是一个实例项目:
5.1 整体项目目录如下:
5.2 grunt配置文件如下:
module.exports = function(grunt) {
grunt.initConfig({
// 清理空文件夹
clean: {
foo1: {
src: ['dist/*']
}
},
ngtemplates: { // 将angular中html模板通过$templateCache进行合并
'angular-my-directives': {
options: {
htmlmin: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true, // Only if you don't use comment directives!
removeEmptyAttributes: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true
},
standalone: true, // 是否创建新的Angular模块
module: 'temp', // 设置创建的Angular模块名字,默认值为target,即'angular-my-directives'
// bootstrap: function (module, script) {
// console.log(script);
// return script;
// },
prefix: '/aa/'
},
src: 'src/**/*.html', // where my view files are
dest: 'dist/tmp.js' // single file of $templateCache
}
},
}); grunt.loadNpmTasks('grunt-angular-templates');
grunt.loadNpmTasks('grunt-contrib-clean'); // 默认被执行的任务列表。
grunt.registerTask('default', [
'clean',
'ngtemplates'
]); };
5.3 button.html和banner.html是两个html模板,其中button.html是button.js中定义的mybutton指令的模板:
button.html代码如下:
<button type="button">{{text}}</button>
button.js代码如下:
var component = angular.module("component", []); component.directive('myButton', myButton);
myButton.$inject = [];
function myButton() {
return {
restrict: 'E',
priority: 999,
scope: {
text: '=',
},
templateUrl: '/aa/src/button.html',
replace: true,
link: function (scope, $element) { }
};
}
banner.html代码如下:
<div style="width: 100%;background-color:blue;height: 70px">This is banner!</div>
5.4 执行grunt命令后,压缩好的tmp.js文件如下:
angular.module('temp', []).run(['$templateCache', function($templateCache) {
'use strict'; $templateCache.put('/aa/src/banner/banner.html',
"<div style=\"width: 100%;background-color:blue;height: 70px\">This is banner!</div>"
); $templateCache.put('/aa/src/button.html',
"<button type=button>{{text}}</button>"
); }]);
5.5 测试用例index.html代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>测试</title>
</head>
<body>
<div ng-controller="DemoCtrl">
<div ng-include="bannerTemplate"></div>
<my-button text="buttonText"></my-button>
</div>
<!-- Load scripts. -->
<script type="text/javascript" src="./lib/jquery.js"></script>
<script type="text/javascript" src="./lib/angular.js"></script>
<script type="text/javascript" src="./dist/tmp.js"></script>
<script type="text/javascript" src="./src/button.js"></script> <script type="text/javascript">
var app = angular.module("test", ["component", "temp"]); app.controller('DemoCtrl', function ($scope) {
$scope.bannerTemplate = '/aa/src/banner/banner.html';
$scope.buttonText = '确认'; }); angular.bootstrap($("html"), ["test"]);
</script>
</body>
</html>
六 源码下载地址
https://gitee.com/bangbangwa/grunt/blob/master/grunt-angular-templates-test.rar
参考资料&内容来源
grunt官网:https://www.npmjs.com/package/grunt-angular-templates
博客园:https://www.cnblogs.com/ms-grf/p/6874256.html
最新文章
- 转载:socket.io 入门
- HTML5 Canvas实现刮刮卡效果实例
- memcached学习——分布式算法(Consistant hash + 虚拟节点)(三)
- 前端新人学习笔记-------html/css/js基础知识点
- Python 第一篇:python简介和入门
- 快速排序Golang版本
- Spring框架学习笔记(7)——代理对象实现AOP
- 修改input属性placeholder的样式
- api大全
- Linux 驱动——Button驱动1
- 力扣算法题—060第K个排列
- JVM监控和调优常用命令工具总结
- reids的主从复制配置
- 升级Ghost
- 查询sql server 表结构
- java 字节流与字符流的区别详解
- 用两条命令看出你买的H3C光模块是否是正品
- 判定一个数num是否为x的幂
- 公司xenserver搭建的使用
- 苹果推送服务器端证书配置.pem生成
热门文章
- Unix/Linux提权漏洞快速检测工具unix-privesc-check
- 洛谷1373小a和uim之大逃离
- 【转】java:多网卡环境下获取MAC地址
- 11G在用EXP导出时,空表不能导出
- Dedecms文章内容页和图片集内容页,调用缩略图的方法
- php 列出当前目录
- tomcat使用安全及CVE-2017-12615
- myeclipse执行tomcat报错Exception in thread &;quot;main&;quot; java.lang.OutOfMemoryError: PermGen space
- dubbo应用程序的单元测试环境搭建(springtest,powermock,mockito)
- Direct-X学习笔记--纹理映射