Skip to content

Instantly share code, notes, and snippets.

@thomastay
Last active November 14, 2021 01:27
Show Gist options
  • Save thomastay/5c0859eae8ec6a08a2c176f1162c8f0b to your computer and use it in GitHub Desktop.
Save thomastay/5c0859eae8ec6a08a2c176f1162c8f0b to your computer and use it in GitHub Desktop.
Esbuild for Node, excluding node_modules starter pack
const chalk = require("chalk");
// Credit to evanw himself: https://github.com/evanw/esbuild/issues/619
const makeAllPackagesExternalPlugin = {
name: "make-all-packages-external",
setup(build) {
const filter = /^[^.\/]|^\.[^.\/]|^\.\.[^\/]/; // Must not start with "/" or "./" or "../"
build.onResolve({ filter }, args => ({
path: args.path,
external: true,
}));
},
};
const outfile = "dist/index.js"; // change me
function toKb(bytes) {
if (typeof bytes !== "number" || Number.isNaN(bytes)) {
throw new Error("bytes must be a number");
}
const kb = Math.ceil(bytes / 1000);
return `${kb}kb`;
}
require("esbuild")
.build({
outfile,
entryPoints: ["index.ts"],
bundle: true,
metafile: true,
platform: "node",
plugins: [makeAllPackagesExternalPlugin],
})
.then(result =>
console.log(
`${outfile}: ${chalk.blueBright(
toKb(result.metafile.outputs[outfile].bytes),
)}`,
),
)
.catch(() => process.exit(1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment