gulp-processConstants.js 1.9 KB

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