prefixLoader.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. Object.defineProperty(exports, '__esModule', { value: true });
  2. const fs = require('fs');
  3. const path = require('path');
  4. const utils = require('@sentry/utils');
  5. /**
  6. * Inject templated code into the beginning of a module.
  7. *
  8. * Options:
  9. * - `templatePrefix`: The XXX in `XXXPrefixLoaderTemplate.ts`, to specify which template to use
  10. * - `replacements`: An array of tuples of the form `[<placeholder>, <replacementValue>]`, used for doing global
  11. * string replacement in the template. Note: The replacement is done sequentially, in the order in which the
  12. * replacement values are given. If any placeholder is a substring of any replacement value besides its own, make
  13. * sure to order the tuples in such a way as to avoid over-replacement.
  14. */
  15. function prefixLoader( userCode) {
  16. // We know one or the other will be defined, depending on the version of webpack being used
  17. const { templatePrefix, replacements } = 'getOptions' in this ? this.getOptions() : this.query;
  18. const templatePath = path.resolve(__dirname, `../templates/${templatePrefix}PrefixLoaderTemplate.js`);
  19. // make sure the template is included when runing `webpack watch`
  20. this.addDependency(templatePath);
  21. // Fill in placeholders
  22. let templateCode = fs.readFileSync(templatePath).toString();
  23. replacements.forEach(([placeholder, value]) => {
  24. // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- user input is escaped
  25. const placeholderRegex = new RegExp(utils.escapeStringForRegex(placeholder), 'g');
  26. templateCode = templateCode.replace(placeholderRegex, value);
  27. });
  28. return `${templateCode}\n${userCode}`;
  29. }
  30. exports.default = prefixLoader;
  31. //# sourceMappingURL=prefixLoader.js.map