2025-03-04 22:11:19 +08:00
|
|
|
import url from "node:url";
|
2023-12-17 19:34:12 +00:00
|
|
|
import { isValidIdentifier } from "@babel/types";
|
2022-10-30 11:14:51 +08:00
|
|
|
import serialize from "serialize-javascript";
|
2022-01-09 01:15:04 +08:00
|
|
|
|
|
|
|
|
export default function esbuildPluginEvaluate() {
|
|
|
|
|
return {
|
|
|
|
|
name: "evaluate",
|
|
|
|
|
setup(build) {
|
2025-04-08 08:18:29 +08:00
|
|
|
build.onLoad(
|
2025-04-16 13:39:48 +08:00
|
|
|
{ filter: /\.evaluate\.[cm]?js$/, namespace: "file" },
|
2025-04-08 08:18:29 +08:00
|
|
|
async ({ path }) => {
|
|
|
|
|
const module = await import(url.pathToFileURL(path));
|
|
|
|
|
const text = Object.entries(module)
|
|
|
|
|
.map(([specifier, value]) => {
|
|
|
|
|
const code =
|
|
|
|
|
value instanceof RegExp
|
|
|
|
|
? `/${value.source}/${value.flags}`
|
|
|
|
|
: serialize(value, { space: 2 });
|
|
|
|
|
|
|
|
|
|
if (specifier === "default") {
|
2025-04-16 13:39:48 +08:00
|
|
|
return `export default ${code};`;
|
2025-04-08 08:18:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!isValidIdentifier(specifier)) {
|
|
|
|
|
throw new Error(`${specifier} is not a valid specifier`);
|
|
|
|
|
}
|
2022-03-13 17:04:06 +08:00
|
|
|
|
2025-04-16 13:39:48 +08:00
|
|
|
return `export const ${specifier} = ${code};`;
|
2025-04-08 08:18:29 +08:00
|
|
|
})
|
|
|
|
|
.join("\n");
|
|
|
|
|
return { contents: text };
|
|
|
|
|
},
|
|
|
|
|
);
|
2022-01-09 01:15:04 +08:00
|
|
|
},
|
|
|
|
|
};
|
|
|
|
|
}
|