replace.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. var jsTokens = require('js-tokens').default;
  3. var processEnvRe = /\bprocess\.env\.[_$a-zA-Z][$\w]+\b/;
  4. var spaceOrCommentRe = /^(?:\s|\/[/*])/;
  5. function replace(src, envs) {
  6. if (!processEnvRe.test(src)) {
  7. return src;
  8. }
  9. var out = [];
  10. var purge = envs.some(function(env) {
  11. return env._ && env._.indexOf('purge') !== -1;
  12. });
  13. jsTokens.lastIndex = 0
  14. var parts = src.match(jsTokens);
  15. for (var i = 0; i < parts.length; i++) {
  16. if (parts[i ] === 'process' &&
  17. parts[i + 1] === '.' &&
  18. parts[i + 2] === 'env' &&
  19. parts[i + 3] === '.') {
  20. var prevCodeToken = getAdjacentCodeToken(-1, parts, i);
  21. var nextCodeToken = getAdjacentCodeToken(1, parts, i + 4);
  22. var replacement = getReplacementString(envs, parts[i + 4], purge);
  23. if (prevCodeToken !== '.' &&
  24. nextCodeToken !== '.' &&
  25. nextCodeToken !== '=' &&
  26. typeof replacement === 'string') {
  27. out.push(replacement);
  28. i += 4;
  29. continue;
  30. }
  31. }
  32. out.push(parts[i]);
  33. }
  34. return out.join('');
  35. }
  36. function getAdjacentCodeToken(dir, parts, i) {
  37. while (true) {
  38. var part = parts[i += dir];
  39. if (!spaceOrCommentRe.test(part)) {
  40. return part;
  41. }
  42. }
  43. }
  44. function getReplacementString(envs, name, purge) {
  45. for (var j = 0; j < envs.length; j++) {
  46. var env = envs[j];
  47. if (typeof env[name] !== 'undefined') {
  48. return JSON.stringify(env[name]);
  49. }
  50. }
  51. if (purge) {
  52. return 'undefined';
  53. }
  54. }
  55. module.exports = replace;