I have the following gulp task:
gulp.task('html', function () {
// Compile templates
return gulp.src(templateFiles)
.pipe(htmlmin({
removeComments: true,
collapseWhitespace: true,
conservativeCollapse: true,
removeScriptTypeAttributes: true
}))
.pipe(ngHtml2Js({
moduleName: 'my.tpls',
prefix: 'tpl/'
}))
.pipe(concat(libName + '.tpls.js'))
.pipe(gulp.dest(destDirectory));
});
Which produces several blocks of code in a file, similar to these:
(function(module) {
try {
module = angular.module('my.tpls');
} catch (e) {
module = angular.module('my.tpls', []);
}
module.run(['$templateCache', function($templateCache) {
$templateCache.put('tpl/my/templates/template1.html',
'<some-html></<some-html>');
}]);
})();
(function(module) {
try {
module = angular.module('my.tpls');
} catch (e) {
module = angular.module('my.tpls', []);
}
module.run(['$templateCache', function($templateCache) {
$templateCache.put('tpl/my/templates/template2.html',
'<some-html></<some-html>');
}]);
})();
This seems very inefficient and sets up a lot of unwanted extra bytes to download.
Is there a way to tweak the gulp task in order to make the result be more like:
(function(module) {
try {
module = angular.module('my.tpls');
} catch (e) {
module = angular.module('my.tpls', []);
}
module.run(['$templateCache', function($templateCache) {
$templateCache.put('tpl/my/templates/template1.html',
'<some-html></<some-html>');
$templateCache.put('tpl/my/templates/template2.html',
'<some-html></<some-html>');
}]);
})();
To clarify; what I'm looking for is the equivalent of the grunt-html2js singleModule option, but for Gulp. I've allready tried adding singleModule: true
in my gulp task options for ngHtml2Js. Didn't work.
I did it by overriding the standard ngHtml2Js template, and use gulp-tap to modify the file afterwards. Works like a charm! :-)
gulp.task('html', function () {
// Compile templates
return gulp.src(templateFiles)
.pipe(htmlmin({
removeComments: true,
collapseWhitespace: true,
conservativeCollapse: true,
removeScriptTypeAttributes: true
}))
.pipe(ngHtml2Js({
template: " $templateCache.put('<%= template.url %>',\n '<%= template.prettyEscapedContent %>');",
prefix: 'tpl/'
}))
.pipe(concat(libName + '.tpls.js'))
.pipe(tap(function(file, t) {
file.contents = Buffer.concat([
new Buffer("(function(module) {\n" +
"try {\n" +
" module = angular.module('my.tpls');\n" +
"} catch (e) {\n" +
" module = angular.module('my.tpls', []);\n" +
"}\n" +
"module.run(['$templateCache', function($templateCache) {\n"),
file.contents,
new Buffer("\n}]);\n" +
"})();\n")
]);
}))
.pipe(gulp.dest(destDirectory));
});