Add extra processing options
This commit is contained in:
51
src/esbuild-babel.ts
Normal file
51
src/esbuild-babel.ts
Normal 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",
|
||||
};
|
||||
});
|
||||
},
|
||||
});
|
Reference in New Issue
Block a user