Skip to content

Instantly share code, notes, and snippets.

@rznewswav
Created June 23, 2023 08:39
Show Gist options
  • Save rznewswav/ac66d648d01ce0b14baa716a75917540 to your computer and use it in GitHub Desktop.
Save rznewswav/ac66d648d01ce0b14baa716a75917540 to your computer and use it in GitHub Desktop.
build from single entrypoint
import * as esbuild from "esbuild";
import esbuildPluginTsc from "esbuild-plugin-tsc";
import path from "path";
import { stat } from "fs/promises";
import ora from "ora";
const main = process.argv.slice(2).find(e => e) ?? "src/main.ts";
const currentFileLocation = import.meta.url.substring("file://".length);
await esbuild.build({
entryPoints: [
main
],
outdir: "dist/src",
sourcemap: true,
bundle: true,
platform: "node",
format: "cjs",
plugins: [esbuildPluginTsc(), {
name: "progress-tracking",
setup(build) {
let spinner = ora();
let filesLoaded = 0;
let compilationStart = 0;
build.onStart(() => {
spinner.text = "Started esbuild";
spinner.start();
compilationStart = performance.now();
});
build.onResolve({
filter: /.*/
}, async args => {
if (!args.path.startsWith(".") || args.resolveDir.includes("node_modules")) {
return {
path: args.path,
external: true
};
}
const pathMaybeNoExt = path.resolve(args.resolveDir, args.path);
const pathNoExt = pathMaybeNoExt.endsWith(".ts") ? pathMaybeNoExt.substring(0, pathMaybeNoExt.length - 3) : pathMaybeNoExt;
const absolutePath = pathNoExt + ".ts";
const absolutePathByIndex = path.join(pathNoExt, "index.ts");
let usingIndex = false;
try {
await stat(absolutePathByIndex);
usingIndex = true;
} catch (ignored) {
}
const usingPath = usingIndex ? absolutePathByIndex : absolutePath;
filesLoaded += 1;
const relativePath = path.relative(currentFileLocation, usingPath).substring(3);
spinner.text = `Resolved ${filesLoaded} files: ${relativePath}`;
});
build.onEnd(() => {
const compilationEnded = performance.now();
const timeTakenMs = compilationEnded - compilationStart;
spinner.succeed(`Compiled ${filesLoaded} files in ${(timeTakenMs / 1000).toFixed(2)}s`);
});
}
}],
target: "es2022"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment