gulp-processConstants.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Dependencies.
  2. var through = require('through2');
  3. var PluginError = require('plugin-error');
  4. const fs = require('fs');
  5. const babylonConstants = require(__dirname + '/../../../dist/preview release/babylon.max').Constants;
  6. /**
  7. * Replace all constants by their inlined values.
  8. */
  9. function processConstants(sourceCode) {
  10. var regexImport = /import { Constants } from .*;/g;
  11. sourceCode = sourceCode.replace(regexImport, "");
  12. var regexConstant = /(?<![_0-9a-zA-Z])Constants\.([_0-9a-zA-Z]*)/g;
  13. var match = regexConstant.exec(sourceCode);
  14. var constantList = [];
  15. while (match) {
  16. var constantName = match[1];
  17. if (constantName && constantName.length > 1) {
  18. constantList.push(constantName);
  19. }
  20. match = regexConstant.exec(sourceCode);
  21. }
  22. for (var constant of constantList) {
  23. var value = babylonConstants[constant];
  24. var regex = new RegExp(`(?<![_0-9a-zA-Z])Constants\.${constant}(?![_0-9a-zA-Z])`, "g");
  25. sourceCode = sourceCode.replace(regex, value);
  26. }
  27. return sourceCode;
  28. }
  29. /**
  30. * Replaces all constants by their inlined values.
  31. */
  32. function main() {
  33. return through.obj(function (file, enc, cb) {
  34. if (file.isNull()) {
  35. cb(null, file);
  36. return;
  37. }
  38. if (file.isStream()) {
  39. cb(new PluginError("Process Constants", "Streaming not supported."));
  40. }
  41. let data = file.contents.toString();
  42. data = processConstants(data);
  43. // Go to disk.
  44. fs.writeFileSync(file.path, data);
  45. return cb();
  46. });
  47. }
  48. module.exports = main;