gulp-processConstants.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 regex = new RegExp(`(?<![_0-9a-zA-Z])Constants\.${constant}(?![_0-9a-zA-Z])`, "g");
  32. var value = babylonConstants[constant];
  33. if (typeof(value) === "string") {
  34. sourceCode = sourceCode.replace(regex, "`" + value + "`");
  35. } else {
  36. sourceCode = sourceCode.replace(regex, value);
  37. }
  38. }
  39. return sourceCode;
  40. }
  41. /**
  42. * Replaces all constants by their inlined values.
  43. */
  44. function main() {
  45. return through.obj(function (file, enc, cb) {
  46. if (file.isNull()) {
  47. cb(null, file);
  48. return;
  49. }
  50. if (file.isStream()) {
  51. cb(new PluginError("Process Constants", "Streaming not supported."));
  52. }
  53. let data = file.contents.toString();
  54. data = processConstants(data);
  55. // Go to disk.
  56. fs.writeFileSync(file.path, data);
  57. return cb();
  58. });
  59. }
  60. module.exports = main;