forked from owlsdepartment/vite-plugin-babel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesbuildBabel.ts
66 lines (56 loc) · 1.74 KB
/
esbuildBabel.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
import babel, { TransformOptions } from '@babel/core';
import { Loader, Plugin, OnLoadArgs, OnLoadResult } from 'esbuild';
import fs from 'fs';
import path from 'path';
/**
* Original: https://github.com/nativew/esbuild-plugin-babel
* Copied, because there was a problem with `type: "module"` in `package.json`
*/
export interface ESBuildPluginBabelOptions {
config?: TransformOptions;
filter?: RegExp;
namespace?: string;
loader?: Loader | ((path: string) => Loader);
}
export const esbuildPluginBabel = (options: ESBuildPluginBabelOptions = {}): Plugin => ({
name: 'babel',
setup(build) {
const { filter = /.*/, namespace = '', config = {}, loader } = options;
const resolveLoader = (args: OnLoadArgs): Loader | undefined => {
if (typeof loader === 'function') {
return loader(args.path);
}
return loader;
};
const transformContents = async (args: OnLoadArgs, contents: string): Promise<OnLoadResult> => {
const babelOptions = babel.loadOptions({
filename: args.path,
...config,
caller: {
name: 'esbuild-plugin-babel',
supportsStaticESM: true,
},
}) as TransformOptions;
if (!babelOptions) {
return { contents, loader: resolveLoader(args) };
}
if (babelOptions.sourceMaps) {
babelOptions.sourceFileName = path.relative(process.cwd(), args.path);
}
return new Promise((resolve, reject) => {
babel.transform(contents, babelOptions, (error, result) => {
error
? reject(error)
: resolve({
contents: result?.code ?? '',
loader: resolveLoader(args),
});
});
});
};
build.onLoad({ filter, namespace }, async args => {
const contents = await fs.promises.readFile(args.path, 'utf8');
return transformContents(args, contents);
});
},
});