Last active
July 30, 2024 22:16
-
-
Save perpil/76ead3015dc2cceec3fd0359988d2070 to your computer and use it in GitHub Desktop.
Minimal esbuild for minifying CloudFront Functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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], | |
| }); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Modify
entryPointsandoutdiras appropriate.When run on these files I got the following results:
intrinsicFunctions.jspresign.jsTo run assuming you have esbuild installed with
npm i --save-dev esbuild:node esbuild-cloudfront.mjs