Skip to content

Instantly share code, notes, and snippets.

@perpil
Last active July 30, 2024 22:16
Show Gist options
  • Select an option

  • Save perpil/76ead3015dc2cceec3fd0359988d2070 to your computer and use it in GitHub Desktop.

Select an option

Save perpil/76ead3015dc2cceec3fd0359988d2070 to your computer and use it in GitHub Desktop.
Minimal esbuild for minifying CloudFront Functions
import * as esbuild from "esbuild";
import * as fs from "fs";
import * as path from "path";
// esbuild plugin to add and remove export from the handler function for cloudfront
let cloudFrontFunctions = {
name: "cloudFrontFunctions",
setup(build) {
const write = build.initialOptions.write;
build.initialOptions.write = false;
// export the handler so esbuild doesn't mangle the function name
build.onLoad({ filter: /\.js$/ }, async (args) => ({
contents: fs
.readFileSync(args.path, "utf-8")
.replace(/(async)?\s+function\s+handler\(/, "export $&"),
}));
// remove export keyword from output file cloudfront functions doesn't support it
build.onEnd((result) => {
result.outputFiles.forEach(
(f) =>
(f.contents = new TextEncoder().encode(
new TextDecoder("utf-8")
.decode(f.contents)
.replaceAll("export ", "")
))
);
if (write === undefined || write) {
result.outputFiles?.forEach((file) => {
fs.mkdirSync(path.dirname(file.path), { recursive: true });
fs.writeFileSync(file.path, file.contents);
});
}
});
},
};
await esbuild.build({
entryPoints: ["cloudfront-functions/*.js"],
target: ["es2017"],
supported: {
generator: false,
},
minify: true,
outdir: "minified",
plugins: [cloudFrontFunctions],
});
@perpil
Copy link
Author

perpil commented Jul 30, 2024

Modify entryPoints and outdir as appropriate.

When run on these files I got the following results:

File Before After Minified Size %
intrinsicFunctions.js 3.6K 1.6K 46.4%
presign.js 8.6K 4.1K 47.7%

To run assuming you have esbuild installed with npm i --save-dev esbuild:

node esbuild-cloudfront.mjs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment