-
Dear devs, How to use tree shaking? My lambda currently is 500k lines long. Kind regards, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
According to esbuild docs, tree-shaking is only enabled either when bundling is enabled or when the output format is set to iife. But can be force-enabled by setting the respective option: import * as lambda from "@aws-cdk/aws-lambda";
import { TypeScriptCode } from "@mrgrain/cdk-esbuild";
const bundledCode = new TypeScriptCode("src/index.ts", {
buildOptions: {
bundle: true, // or
treeShaking: true,
}
});
const fn = new lambda.Function(stack, "MyFunction", {
runtime: lambda.Runtime.NODEJS_14_X,
handler: "index.handler",
code: bundledCode,
}); Please let me know if that works for you! It also should work with new InlineTypeScriptCode("const code: number = 1 + 2;", {
buildOptions: {
treeShaking: true,
},
}); See: |
Beta Was this translation helpful? Give feedback.
-
Ah yes, I see. This will be because of this: Long story short, esbuild doesn't know what parts of the SDK to "shake". You will have to change how you import E.g. to use S3 you will have to write import S3 from "aws-sdk/clients/s3"; instead. Alternatively, because you're creating a Lambda, you can mark new TypeScriptCode("./src/index.tsx", {
buildOptions: {
external: ["aws-sdk"],
},
}); |
Beta Was this translation helpful? Give feedback.
Ah yes, I see. This will be because of this:
import * as AWS from 'aws-sdk'
Long story short, esbuild doesn't know what parts of the SDK to "shake". You will have to change how you import
aws-sdk
. AWS has written a good blog post about this: https://aws.amazon.com/blogs/developer/modular-packages-in-aws-sdk-for-javascript/E.g. to use S3 you will have to write
instead.
Alternatively, because you're creating a Lambda, you can mark
aws-sdk
asexternal
und fallback to the version that comes pre-installed on Lambda: