templateCache.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const path = require('path');
  2. const gutil = require('gulp-util');
  3. const through = require('through2');
  4. const minify = require('html-minifier').minify;
  5. function replacePlugin(contents, objName) {
  6. const re = new RegExp(`${objName}\\.get\\('(.*?)'\\)`, 'g');
  7. return through.obj(function (file, enc, cb) {
  8. const dirname = path.dirname(file.path);
  9. file.contents = new Buffer(String(file.contents).replace(re, (m, name) => {
  10. const filepath = path.resolve(dirname, name);
  11. const item = contents[filepath];
  12. if (!item) throw new Error(`\
  13. Cache not found: ${name}
  14. Required by:
  15. - ${file.path}`);
  16. return `${objName}.get(${item.id})`;
  17. }));
  18. cb(null, file);
  19. });
  20. }
  21. module.exports = function templateCache(objName) {
  22. const contentTpl = `${objName}.put(<%= name %>, <%= content %>);\n`;
  23. const header = `\n\n/* Templates cached with love :) */\n`;
  24. const contents = {};
  25. function bufferContents(file, enc, cb) {
  26. if (file.isNull()) return cb();
  27. if (file.isStream()) return this.emit('error', new gutil.PluginError('VM-cache', 'Stream is not supported.'));
  28. contents[file.path] = {
  29. content: minify(String(file.contents), {
  30. removeComments: true,
  31. collapseWhitespace: true,
  32. conservativeCollapse: true,
  33. removeAttributeQuotes: true,
  34. }),
  35. };
  36. cb();
  37. }
  38. function endStream(cb) {
  39. var keys = Object.keys(contents).sort();
  40. keys.forEach((key, i) => contents[key].id = i + 1);
  41. this.replace = () => replacePlugin(contents, objName);
  42. const templates = keys.map(key => {
  43. const item = contents[key];
  44. return `${objName}.put(${item.id}, ${JSON.stringify(item.content)});`;
  45. }).join('\n');
  46. this.push(new gutil.File({
  47. base: '',
  48. path: 'template.js',
  49. contents: new Buffer(header + templates),
  50. }));
  51. cb();
  52. }
  53. return through.obj(bufferContents, endStream);
  54. };