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