gulp-appendSrcToVariable.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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, moduleType) {
  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. // construct concat instance
  25. if (!content) {
  26. content = "";
  27. }
  28. // set first file if not already set
  29. if (!firstFile) {
  30. if (moduleType === "es6") {
  31. content += `
  32. // import * as BABYLON from 'babylonjs/core/es6';
  33. `;
  34. }
  35. firstFile = file;
  36. }
  37. var name = namingCallback(file.relative);
  38. if (moduleType) {
  39. let vars = varName.split(".");
  40. // shader support when using modules
  41. if (moduleType === "es6") {
  42. content += `
  43. let ${name} = ${JSON.stringify(file.contents.toString())};
  44. // ${varName}["${name}"] = ${varName}["${name}"] || ${name};
  45. export { ${name} };
  46. `;
  47. } else {
  48. // commonjs
  49. content += `
  50. if(typeof require !== 'undefined'){
  51. var BABYLON = require("babylonjs/core");
  52. let data = ${JSON.stringify(file.contents.toString())};
  53. ${varName}["${name}"] = ${varName}["${name}"] || data;
  54. module.exports = module.exports || {};
  55. module.exports["${name}"] = data;
  56. }
  57. `;
  58. }
  59. } else {
  60. content += varName + "['" + name + "'] = " + JSON.stringify(file.contents.toString()) + ";\r\n";
  61. }
  62. cb();
  63. }
  64. function endStream(cb) {
  65. if (!firstFile || !content) {
  66. cb();
  67. return;
  68. }
  69. var pathObject = path.parse(firstFile.path);
  70. var joinedPath = path.join(pathObject.dir, output);
  71. var joinedFile = new File({
  72. cwd: firstFile.cwd,
  73. base: firstFile.base,
  74. path: joinedPath,
  75. contents: Buffer.from(content)
  76. });
  77. this.push(joinedFile);
  78. cb();
  79. }
  80. return through.obj(bufferContents, endStream);
  81. }
  82. module.exports = appendSrcToVariable;