在angular应用程序开发的过程中经常使用到template和templateUrl,最后产品发布的时候这些template最终都是要被打包到一个js文件中的,下载了老外写的一个angular-ui-bootstrap的项目,发现老外是使用了一个html2js的库再结合grunt把template转换成一个调用templateCache的代码,通过调用templateCache把模板字符串预先注册到缓存
angular-ui-bootstrap 部分 template 代码
<div class="alert" ng-class="['alert-' + (type || 'warning'), closeable ? 'alert-dismissible' : null]" role="alert">
<button ng-show="closeable" type="button" class="close" ng-click="close({$event: $event})">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<div ng-transclude></div>
</div>
经过html2js转换过的代码
angular.module("uib/template/alert/alert.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("uib/template/alert/alert.html",
"<div class=\"alert\" ng-class=\"['alert-' + (type || 'warning'), closeable ? 'alert-dismissible' : null]\" role=\"alert\">\n" +
" <button ng-show=\"closeable\" type=\"button\" class=\"close\" ng-click=\"close({$event: $event})\">\n" +
" <span aria-hidden=\"true\">×</span>\n" +
" <span class=\"sr-only\">Close</span>\n" +
" </button>\n" +
" <div ng-transclude></div>\n" +
"</div>\n" +
"");
}]);
angular-ui-bootstrap的构建思路就是把template文件转换成注册angular templateCache的代码并合并到目标构建文件在模板被使用之前注册templateCache。
虽然了解了angular-ui-bootstrap的构建思路,不过我使用的是webpack来构建,需要用webpack的思路来解决问题,主要思路就是在注册指令时直接 require template文件得到字符串并传递给注册指令时所需要的template参数,
首先想到的是url-loader加载器,使用url-loader加载器可以把template文件转换成一个base64编码的url地址,而且angular注册指令的时候支持 templateUrl参数,感觉理论上应该可以,不过我并没有尝试,因为url-loader对文件的大小有限制。
上npm搜索了html-loader 找到了一个加载器 html-tpl-loader 安装之后修改加载器配置
添加
{ test: /\.html$/, loader: "html-tpl" },
尝试加载template成功返回一个函数,调用该函数即获得template字符串传递给angular就可以顺利创建指令了
加载模板
var tpl=require("./kmuiLayout.html")() /*加载模板*/
在指令中使用模板
kmSystem.directive('kmuiLayout',function(){
return{
restrict: 'E',
template:tpl,
注:模板放在和js文件同层的目录下