UNPKG

1.21 kBPlain TextView Raw
1import * as validateOptions from 'schema-utils';
2import { getOptions } from 'loader-utils';
3import { Compiler } from 'webpack';
4
5const schema = {
6 type: 'object' as const,
7 properties: {},
8 additionalProperties: false,
9};
10
11function reloadGenerator(name: string) {
12 delete require.cache[require.resolve(name)];
13 return require(name);
14}
15
16export interface DependencyOptions {
17 includedInParent?: boolean;
18}
19
20export default async function loader(source: string, map: string, meta: any) {
21 const options = getOptions(this);
22
23 validateOptions(schema, options, {
24 name: 'Codegen Loader',
25 baseDataPath: 'options',
26 });
27
28 const name = this.resourcePath;
29 const compiler = this._compiler as Compiler;
30 const callback = this.async();
31 const generator = reloadGenerator(name);
32 const content = await generator.call({
33 name,
34 options: {
35 outDir: compiler?.options?.output?.path,
36 rootDir: process.cwd(),
37 },
38 addDependency: (file: string, options: DependencyOptions = {}) => this.addDependency(file),
39 });
40
41 if (typeof content === 'string') {
42 callback(null, content, map, meta);
43 } else {
44 callback(new Error('Unsupported return type from codegen.'), source);
45 }
46}