templateCache.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const gutil = require('gulp-util');
  3. const through = require('through2');
  4. const _ = require('underscore');
  5. const minify = require('html-minifier').minify;
  6. module.exports = function templateCache() {
  7. const contentTpl = 'cache.put(<%= name %>, <%= content %>);\n';
  8. const header = `/* Templates cached with love :) */
  9. define('templates', function (require, exports, module) {
  10. var cache = require('cache');
  11. `;
  12. const footer = `
  13. });
  14. `;
  15. const contents = [];
  16. function bufferContents(file, enc, cb) {
  17. if (file.isNull()) return cb();
  18. if (file.isStream())
  19. return this.emit('error', new gutil.PluginError('VM-cache', 'Stream is not supported.'));
  20. contents.push(gutil.template(contentTpl, {
  21. name: JSON.stringify(('/' + file.relative).replace(/\\/g, '/')),
  22. content: JSON.stringify(minify(String(file.contents), {
  23. removeComments: true,
  24. collapseWhitespace: true,
  25. conservativeCollapse: true,
  26. removeAttributeQuotes: true,
  27. })),
  28. file: '',
  29. }));
  30. cb();
  31. }
  32. function endStream(cb) {
  33. this.push(new gutil.File({
  34. base: '',
  35. path: 'template.js',
  36. contents: new Buffer(header + contents.join('') + footer),
  37. }));
  38. cb();
  39. }
  40. return through.obj(bufferContents, endStream);
  41. };