@darkobits/saffron
Version:
Yargs + Cosmiconfig for robust, configurable CLIs.
71 lines (70 loc) • 2.64 kB
JavaScript
import fs from "fs/promises";
import path from "path";
import { TsconfigPathsPlugin } from "@esbuild-plugins/tsconfig-paths";
import * as esbuild from "esbuild";
import { nodeExternalsPlugin } from "esbuild-node-externals";
import { getTsconfig } from "get-tsconfig";
import log from "../../log.js";
const EXT_MAP = {
".js": ".js",
".ts": ".js",
".tsx": ".js",
".jsx": " .js",
// User explicitly wants CommonJS.
".cjs": ".cjs",
".cts": ".cjs",
// User explicitly wants ESM.
".mjs": ".mjs",
".mts": ".mjs"
};
async function esbuildStrategy(filePath, opts) {
var _a;
const prefix = log.chalk.green("strategy:esbuild");
const parsedFilePath = path.parse(filePath);
const isExplicitCommonJs = [".cjs", ".cts"].includes(parsedFilePath.ext);
const isExplicitESM = [".mjs", ".mts"].includes(parsedFilePath.ext);
const outExt = EXT_MAP[parsedFilePath.ext];
if (!outExt)
throw new Error(`${prefix} Unable to determine output file extension from input extension: ${parsedFilePath.ext}`);
const format = isExplicitESM ? "esm" : isExplicitCommonJs ? "cjs" : opts.pkg.type === "module" ? "esm" : "cjs";
log.verbose(prefix, `Using format: ${log.chalk.bold(format)}`);
const tempFileName = `.${parsedFilePath.name}.${Date.now()}${outExt}`;
const tempFilePath = path.join(path.dirname(filePath), tempFileName);
log.verbose(prefix, `Temporary file path: ${log.chalk.green(tempFilePath)}`);
try {
const buildOptions = {
entryPoints: [filePath],
target: "node16",
outfile: tempFilePath,
format,
platform: "node",
bundle: true,
plugins: [
nodeExternalsPlugin({
packagePath: path.resolve(opts.pkg.root ?? "", "package.json")
})
]
};
const tsConfigResult = getTsconfig(filePath);
if (tsConfigResult) {
const tsconfig = tsConfigResult.path;
log.verbose(prefix, "Using TypeScript configuration:", log.chalk.green(tsconfig));
buildOptions.tsconfig = tsconfig;
(_a = buildOptions.plugins) == null ? void 0 : _a.push(TsconfigPathsPlugin({ tsconfig }));
}
await esbuild.build(buildOptions);
} catch (err) {
throw new Error(`${log.chalk.red(`[${prefix}] Failed to transpile ${filePath}:`)} ${err.message}`, { cause: err });
}
try {
return await import(tempFilePath);
} catch (err) {
throw new Error(`${log.chalk.red(`[${prefix}] Failed to import() ${filePath}:`)} ${err.message}`, { cause: err });
} finally {
await fs.access(tempFilePath, fs.constants.F_OK).then(() => fs.unlink(tempFilePath));
}
}
export {
esbuildStrategy
};
//# sourceMappingURL=esbuild.js.map