Skip to content

Commit 22fab0f

Browse files
committed
parameterize prefix loader template name and replacement values
1 parent a282b8c commit 22fab0f

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed
Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,38 @@
1+
import { escapeStringForRegex } from '@sentry/utils';
12
import * as fs from 'fs';
23
import * as path from 'path';
34

45
import { LoaderThis } from './types';
56

67
type LoaderOptions = {
7-
distDir: string;
8+
templatePrefix: string;
9+
replacements: Array<[string, string]>;
810
};
911

1012
/**
1113
* 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.
1221
*/
1322
export default function prefixLoader(this: LoaderThis<LoaderOptions>, userCode: string): string {
1423
// 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;
1625

17-
const templatePath = path.resolve(__dirname, '../templates/prefixLoaderTemplate.js');
26+
const templatePath = path.resolve(__dirname, `../templates/${templatePrefix}PrefixLoaderTemplate.js`);
1827
// make sure the template is included when runing `webpack watch`
1928
this.addDependency(templatePath);
2029

21-
// Fill in the placeholder
30+
// Fill in placeholders
2231
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+
});
2436

2537
return `${templateCode}\n${userCode}`;
2638
}

0 commit comments

Comments
 (0)