inject-loader.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Note: this is based on https://github.com/plasticine/inject-loader,
  2. // patched to make istanbul work properly
  3. const loaderUtils = require("loader-utils");
  4. const QUOTE_REGEX_STRING = "['|\"]{1}";
  5. const hasOnlyExcludeFlags = query => Object.keys(query).filter(key => query[key] === true).length === 0;
  6. const escapePath = path => path.replace("/", "\\/");
  7. function createRequireStringRegex(query) {
  8. const regexArray = [];
  9. // if there is no query then replace everything
  10. if (Object.keys(query).length === 0) {
  11. regexArray.push("([^\\)]+)");
  12. } else if (hasOnlyExcludeFlags(query)) {
  13. // if there are only negation matches in the query then replace everything
  14. // except them
  15. Object.keys(query).forEach(key => regexArray.push(`(?!${QUOTE_REGEX_STRING}${escapePath(key)})`));
  16. regexArray.push("([^\\)]+)");
  17. } else {
  18. regexArray.push(`(${QUOTE_REGEX_STRING}(`);
  19. regexArray.push(Object.keys(query).map(key => escapePath(key)).join("|"));
  20. regexArray.push(`)${QUOTE_REGEX_STRING})`);
  21. }
  22. // Wrap the regex to match `require()`
  23. regexArray.unshift("require\\(");
  24. regexArray.push("\\)");
  25. return new RegExp(regexArray.join(""), "g");
  26. }
  27. module.exports = function inject(src) {
  28. if (this.cacheable) {
  29. this.cacheable();
  30. }
  31. const regex = createRequireStringRegex(loaderUtils.getOptions(this) || {});
  32. return `module.exports = function inject(injections) {
  33. var module = {exports: {}};
  34. var exports = module.exports;
  35. ${src.replace(regex, "(injections[$1] || /* istanbul ignore next */ $&)")}
  36. return module.exports;
  37. }\n`;
  38. };