Skip to content

Instantly share code, notes, and snippets.

@mhyland-phoenicia
Last active January 31, 2024 17:53
Show Gist options
  • Save mhyland-phoenicia/c16ed0907c264fc767215e6cb214e5ef to your computer and use it in GitHub Desktop.
Save mhyland-phoenicia/c16ed0907c264fc767215e6cb214e5ef to your computer and use it in GitHub Desktop.
Bundle Lambdas in parallel for CDK nodejs typescript
import { build } from "esbuild";
import * as glob from "glob";
import * as path from "path";
import { promises as fs } from "fs"; // Use the promises API of fs
const handlersDir = "{PATH_TO_LAMBDA_FOLDER}";
export async function bundleLambdas() {
const start = performance.now();
await clearDist();
const entryFiles = (
await Promise.all(
glob.sync(`${handlersDir}/**/*.ts`, { dot: true }).map(async (file) => {
return (await hasHandlerFunction(file)) ? file : null;
}),
)
).filter(Boolean); // This will filter out null values, leaving only files with exports.handler
const buildTasks = entryFiles.map((file: any) => {
const relativePath = path.relative(handlersDir, file);
const directoryName = path.dirname(relativePath);
const fileNameWithoutExtension = path.basename(file, ".ts");
return build({
entryPoints: [file],
bundle: true,
outdir: `./dist/${directoryName}/${fileNameWithoutExtension}`,
platform: "node",
external: ["@aws-sdk/*"],
});
});
// Run all builds in parallel
await Promise.all(buildTasks)
.then(() => {
const end = performance.now();
const duration = (end - start) / 1000;
console.error(`\n✨ Lambda Bundle time: ${duration.toFixed(2)}s\n`);
})
.catch((err) => {
console.error("Build error:", err);
process.exit(1);
});
}
async function clearDist() {
try {
await fs.rm("./dist", { recursive: true });
} catch (err) {
console.error("Error clearing dist folder:");
}
try {
await fs.mkdir("./dist", { recursive: true });
} catch {
console.error("Error creating dist folder:");
}
}
async function hasHandlerFunction(file: any) {
const content = await fs.readFile(file, "utf-8");
return content.includes("exports.handler");
}
bundleLambdas();
// bundle lambdas before running cdk root file
{
"app": "npx ts-node bin/bundleLambdas.ts && npx ts-node --prefer-ts-exts bin/cdk-main.ts",
//...
}
// use fromAsset to grab prebuilt lambda
const lambdaFunction = new lambda.Function(this, ${id}`, {
code: lambda.Code.fromAsset(`dist/${id}`),
handler: `${id.split("/").pop()}.handler`,
runtime: lambda.Runtime.NODEJS_18_X
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment