Skip to content

Instantly share code, notes, and snippets.

@juniorplenty
Last active August 29, 2015 14:11
Show Gist options
  • Save juniorplenty/a89b2f73f0f79daf18b4 to your computer and use it in GitHub Desktop.
Save juniorplenty/a89b2f73f0f79daf18b4 to your computer and use it in GitHub Desktop.
gulp-angular-templatecache alternative
// This implementation eliminates the plugin, and breaks out the conversion-to-javascript (6 lines) and
// concat-into-template.js (3 lines)
// This way, the file is parsed by jade, converted to javascript, and then cached. The concat/header/footer
// workflow then takes all cached content and creates the final file.
// Enjoy.
var htmlJsStr = require('js-string-escape'); // used by templatecache internally
var cache = require('gulp-cached');
function buildTemplates(){
return gulp.src(paths.source.templates)
.pipe(rename(function(path){
path.dirname = path.dirname.replace( 'javascripts/directives/templates'
, 'templates'
);
}))
.pipe(cache('templates'))
.pipe(jade())
.pipe(rename(function(path){ path.extname = '.jade'; }))
.pipe(tap(function(file){
file.contents = new Buffer( '$templateCache.put("'
+ file.path.replace(file.base,'')
+ '","'
+ htmlJsStr(file.contents)
+ '");'
);
}))
.pipe(remember('templates'))
.pipe(concat(paths.build.templates))
.pipe(header('angular.module("ofp").run(["$templateCache", function($templateCache) {\n'))
.pipe(footer('\n}]);'))
.pipe(gulp.dest(paths.build.tmp));
}
// gulp-angular-templatecache modifies the original contents of the file with contents that have been converted
// to javascript.
// if you're attempting to cache jade compilation in a watch, the contents of the cached file will
// actually be javascript.
// on subsequent runs, "remember" retrieves the cached file with javascript contents, and
// templatecache re-processes that javascript, when it really needs to process the original html (or not
// reprocess at all)
// this causes the template.js contents to gradually become a set of nested-escaped javascript strings, instead
// of simple escaped html strings
function buildTemplates(){
return gulp.src(paths.source.templates)
.pipe(rename(function(path){
path.dirname = path.dirname.replace( 'javascripts/directives/templates'
, 'templates'
);
}))
.pipe(cache('templates'))
.pipe(jade())
.pipe(rename(function(path){ path.extname = '.jade'; }))
.pipe(remember('templates')) // this restores the already-template-cached content, i.e. javascript
.pipe(templateCache(paths.build.templates,{ module : 'ofp' })) // this re-javascriptifies the already-javascriptified content!!
.pipe(gulp.dest(paths.build.tmp));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment