prefixLoader.js 1.6 KB

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