-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathprefixLoader.ts
34 lines (28 loc) · 1014 Bytes
/
prefixLoader.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import * as fs from 'fs';
import * as path from 'path';
type LoaderOptions = {
distDir: string;
};
// TODO Use real webpack types
type LoaderThis = {
// Webpack 4
query?: LoaderOptions;
// Webpack 5
getOptions?: () => LoaderOptions;
addDependency: (filepath: string) => void;
};
/**
* Inject templated code into the beginning of a module.
*/
function prefixLoader(this: LoaderThis, userCode: string): string {
// We know one or the other will be defined, depending on the version of webpack being used
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { distDir } = this.getOptions ? this.getOptions() : this.query!;
const templatePath = path.resolve(__dirname, 'prefixLoaderTemplate.js');
this.addDependency(templatePath);
// Fill in the placeholder
let templateCode = fs.readFileSync(templatePath).toString();
templateCode = templateCode.replace('__DIST_DIR__', distDir);
return `${templateCode}\n${userCode}`;
}
export { prefixLoader as default };