-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
esbuildBabelPluginIstanbul.ts
38 lines (31 loc) · 1.13 KB
/
esbuildBabelPluginIstanbul.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
import { transformFileAsync } from '@babel/core';
import { OnLoadArgs, OnLoadOptions, OnLoadResult, Plugin } from 'esbuild';
import { join } from 'path';
import { fileURLToPath } from 'url';
export type Predicate = (args: OnLoadArgs) => boolean;
export type IstanbulPluginConfig = {
filter: OnLoadOptions['filter'];
loader: OnLoadResult['loader'];
name: Plugin['name'];
predicate?: Predicate | undefined;
};
export const defaultPredicate: Predicate = args => !args.path.includes('/node_modules/');
export const babelPlugin = ({ filter, loader, name, predicate = defaultPredicate }: IstanbulPluginConfig): Plugin => ({
name,
setup(build) {
build.onLoad({ filter }, async args => {
if (!predicate(args)) {
return;
}
const result = await transformFileAsync(args.path, {
configFile: join(fileURLToPath(import.meta.url), '../babel.profile.config.json'),
rootMode: 'root',
sourceFileName: args.path
});
if (!result?.code) {
throw new Error(`Failed to add instrumentation code to ${args.path}.`);
}
return { contents: result.code, loader };
});
}
});