-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
loader.ts
83 lines (74 loc) · 1.93 KB
/
loader.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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import path from 'path';
import {
transform as defaultEsbuildTransform,
type TransformOptions,
} from 'esbuild';
import { getOptions } from 'loader-utils';
import webpack from 'webpack';
import {
getTsconfig,
parseTsconfig,
createFilesMatcher,
type TsConfigResult,
type FileMatcher,
} from 'get-tsconfig';
import type { LoaderOptions } from './types.js';
let foundTsconfig: TsConfigResult | null;
let fileMatcher: FileMatcher;
async function ESBuildLoader(
this: webpack.loader.LoaderContext,
source: string,
): Promise<void> {
const done = this.async()!;
const options: LoaderOptions = getOptions(this);
const {
implementation,
tsconfig,
...esbuildTransformOptions
} = options;
if (implementation && typeof implementation.transform !== 'function') {
done(
new TypeError(
`esbuild-loader: options.implementation.transform must be an ESBuild transform function. Received ${typeof implementation.transform}`,
),
);
return;
}
const transform = implementation?.transform ?? defaultEsbuildTransform;
const transformOptions = {
...esbuildTransformOptions,
target: options.target ?? 'es2015',
loader: options.loader ?? 'default',
sourcemap: this.sourceMap,
sourcefile: this.resourcePath,
};
if (!('tsconfigRaw' in transformOptions)) {
if (!fileMatcher) {
const tsconfigPath = tsconfig && path.resolve(tsconfig);
foundTsconfig = (
tsconfigPath
? {
config: parseTsconfig(tsconfigPath),
path: tsconfigPath,
}
: getTsconfig()
);
if (foundTsconfig) {
fileMatcher = createFilesMatcher(foundTsconfig);
}
}
if (fileMatcher) {
transformOptions.tsconfigRaw = fileMatcher(
// Doesn't include query
this.resourcePath,
) as TransformOptions['tsconfigRaw'];
}
}
try {
const { code, map } = await transform(source, transformOptions);
done(null, code, map && JSON.parse(map));
} catch (error: unknown) {
done(error as Error);
}
}
export default ESBuildLoader;