index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. 'use strict';
  2. var through = require('through2');
  3. var path = require('path');
  4. var File = require('vinyl');
  5. var Concat = require('concat-with-sourcemaps');
  6. // file can be a vinyl file object or a string
  7. // when a string it will construct a new one
  8. module.exports = function(file, opt) {
  9. if (!file) {
  10. throw new Error('gulp-concat: Missing file option');
  11. }
  12. opt = opt || {};
  13. // to preserve existing |undefined| behaviour and to introduce |newLine: ""| for binaries
  14. if (typeof opt.newLine !== 'string') {
  15. opt.newLine = '\n';
  16. }
  17. var isUsingSourceMaps = false;
  18. var latestFile;
  19. var latestMod;
  20. var fileName;
  21. var concat;
  22. if (typeof file === 'string') {
  23. fileName = file;
  24. } else if (typeof file.path === 'string') {
  25. fileName = path.basename(file.path);
  26. } else {
  27. throw new Error('gulp-concat: Missing path in file options');
  28. }
  29. function bufferContents(file, enc, cb) {
  30. // ignore empty files
  31. if (file.isNull()) {
  32. cb();
  33. return;
  34. }
  35. // we don't do streams (yet)
  36. if (file.isStream()) {
  37. this.emit('error', new Error('gulp-concat: Streaming not supported'));
  38. cb();
  39. return;
  40. }
  41. // enable sourcemap support for concat
  42. // if a sourcemap initialized file comes in
  43. if (file.sourceMap && isUsingSourceMaps === false) {
  44. isUsingSourceMaps = true;
  45. }
  46. // set latest file if not already set,
  47. // or if the current file was modified more recently.
  48. if (!latestMod || file.stat && file.stat.mtime > latestMod) {
  49. latestFile = file;
  50. latestMod = file.stat && file.stat.mtime;
  51. }
  52. // construct concat instance
  53. if (!concat) {
  54. concat = new Concat(isUsingSourceMaps, fileName, opt.newLine);
  55. }
  56. // add file to concat instance
  57. concat.add(file.relative, file.contents, file.sourceMap);
  58. cb();
  59. }
  60. function endStream(cb) {
  61. // no files passed in, no file goes out
  62. if (!latestFile || !concat) {
  63. cb();
  64. return;
  65. }
  66. var joinedFile;
  67. // if file opt was a file path
  68. // clone everything from the latest file
  69. if (typeof file === 'string') {
  70. joinedFile = latestFile.clone({contents: false});
  71. joinedFile.path = path.join(latestFile.base, file);
  72. } else {
  73. joinedFile = new File(file);
  74. }
  75. joinedFile.contents = concat.content;
  76. if (concat.sourceMapping) {
  77. joinedFile.sourceMap = JSON.parse(concat.sourceMap);
  78. }
  79. this.push(joinedFile);
  80. cb();
  81. }
  82. return through.obj(bufferContents, endStream);
  83. };