gulp-appendSrcToVariable.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. var through = require('through2');
  2. var gutil = require('gulp-util');
  3. var PluginError = gutil.PluginError;
  4. var path = require('path');
  5. var File = gutil.File;
  6. // Consts
  7. const PLUGIN_NAME = 'gulp-appendSrcToVariable';
  8. var appendSrcToVariable = function appendSrcToVariable(varName, namingCallback, output) {
  9. var content;
  10. var firstFile;
  11. namingCallback = namingCallback || function (filename) { return filename; };
  12. function bufferContents(file, enc, cb) {
  13. // ignore empty files
  14. if (file.isNull()) {
  15. cb();
  16. return;
  17. }
  18. // no stream support, only files.
  19. if (file.isStream()) {
  20. this.emit('error', new PluginError('gulp-concat', 'Streaming not supported'));
  21. cb();
  22. return;
  23. }
  24. // set first file if not already set
  25. if (!firstFile) {
  26. firstFile = file;
  27. }
  28. // construct concat instance
  29. if (!content) {
  30. content = "";
  31. }
  32. var name = namingCallback(file.relative);
  33. content += varName + "['" + name + "'] = " + JSON.stringify(file.contents.toString()) + ";\r\n";
  34. cb();
  35. }
  36. function endStream(cb) {
  37. if (!firstFile || !content) {
  38. cb();
  39. return;
  40. }
  41. var pathObject = path.parse(firstFile.path);
  42. var joinedPath = path.join(pathObject.dir, output);
  43. var joinedFile = new File({
  44. cwd: firstFile.cwd,
  45. base: firstFile.base,
  46. path: joinedPath,
  47. contents: new Buffer(content)
  48. });
  49. this.push(joinedFile);
  50. cb();
  51. }
  52. return through.obj(bufferContents, endStream);
  53. }
  54. module.exports = appendSrcToVariable;