Add extra processing options

This commit is contained in:
Alex
2024-04-06 21:04:33 -04:00
parent 8c789367af
commit ee14d81e8e
4 changed files with 140 additions and 72 deletions

51
src/esbuild-babel.ts Normal file
View File

@ -0,0 +1,51 @@
import { readFileSync } from "node:fs";
import { extname } from "node:path";
import { once } from "lodash";
import type babel from "@babel/core";
import type * as esbuild from "esbuild";
import { transformSync } from "@babel/core";
/**
* An esbuild plugin that processes files with Babel if `getPlugins` returns any plugins.
*/
export const babelPlugin = ({
filter = /\.[jt]sx?$/,
plugins: getPlugins,
}: {
filter?: RegExp;
plugins:
| babel.PluginItem[]
| ((file: { path: string; contents: string }) => babel.PluginItem[]);
}): esbuild.Plugin => ({
name: "babel-plugin",
setup(build) {
build.onLoad({ filter }, ({ path }) => {
const load = once(() => readFileSync(path, "utf-8"));
const plugins = Array.isArray(getPlugins)
? getPlugins
: getPlugins({
path,
get contents() {
return load();
},
});
if (!plugins.length) {
return;
}
const { code } = transformSync(load(), {
parserOpts: {
plugins: ["jsx", "decorators", "typescript", "importAttributes"],
},
filename: path,
plugins,
})!;
return {
contents: code!,
loader: extname(path).slice(1) as "js" | "ts",
};
});
},
});