1 | var util = require("util");
|
2 | var es = require("event-stream");
|
3 |
|
4 | var TEMPLATE = 'angular.module(\'%s\', []).run(function($templateCache) {\n' +
|
5 | ' $templateCache.put(\'%s\',\n \'%s\');\n' +
|
6 | '});\n';
|
7 |
|
8 | var SINGLE_MODULE_TPL = '(function(module) {\n' +
|
9 | 'try {\n' +
|
10 | ' module = angular.module(\'%s\');\n' +
|
11 | '} catch (e) {\n' +
|
12 | ' module = angular.module(\'%s\', []);\n' +
|
13 | '}\n' +
|
14 | 'module.run(function($templateCache) {\n' +
|
15 | ' $templateCache.put(\'%s\',\n \'%s\');\n' +
|
16 | '});\n' +
|
17 | '})();\n';
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | module.exports = function(options){
|
27 | "use strict";
|
28 |
|
29 | function ngHtml2Js(file, callback){
|
30 | if(file.isStream()){
|
31 | return callback(new Error("gulp-ng-html2js: Streaming not supported"));
|
32 | }
|
33 |
|
34 | if(file.isBuffer()){
|
35 | var filePath = getFileUrl(file, options);
|
36 | file.contents = new Buffer(generateModuleDeclaration(filePath, String(file.contents), options));
|
37 | file.path = file.path.replace(".html", ".js");
|
38 | }
|
39 |
|
40 | return callback(null, file);
|
41 | }
|
42 |
|
43 | |
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 | function generateModuleDeclaration(fileUrl, contents, options){
|
52 | var escapedContent = escapeContent(contents);
|
53 | if(options && options.moduleName){
|
54 | return util.format(SINGLE_MODULE_TPL, options.moduleName, options.moduleName, fileUrl, escapedContent);
|
55 | }
|
56 | else{
|
57 | return util.format(TEMPLATE, fileUrl, fileUrl, escapedContent);
|
58 | }
|
59 | }
|
60 |
|
61 | |
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 | function getFileUrl(file, options){
|
70 |
|
71 | var url = file.relative;
|
72 |
|
73 |
|
74 | url = url.replace(/\\/g, '/');
|
75 |
|
76 |
|
77 | if(options && options.stripPrefix && url.indexOf(options.stripPrefix) === 0){
|
78 | url = url.replace(options.stripPrefix, '');
|
79 | }
|
80 |
|
81 | if(options && options.prefix){
|
82 | url = options.prefix + url;
|
83 | }
|
84 |
|
85 | return url;
|
86 | }
|
87 |
|
88 | |
89 |
|
90 |
|
91 |
|
92 |
|
93 | function escapeContent(content){
|
94 | return content.replace(/\\/g, '\\\\').replace(/'/g, '\\\'').replace(/\r?\n/g, '\\n\' +\n \'');
|
95 | }
|
96 |
|
97 | return es.map(ngHtml2Js);
|
98 | };
|