Sharing Typescript code between AWS Lambda with AWS SAM CLI
faridz974
Posted on July 8, 2022
Introduction
Recently, Amazon has released a beta version of AWS SAM CLI with the support of Typescript.
The sample works well when you have a simple use case.
Now, imagine that you want to have multiple AWS Lambda in your repository and have to share your code.
The goal of this post is to continue using SAM CLI to build and deploy your Typescript code.
Default configuration
By default, you can notice that the CodeUri property is referencing only your function folder.
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs16.x
and your code is like the following:
import type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda';
import { helloWorld } from '../shared/hello';
export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
return {
statusCode: 200,
body: JSON.stringify({
message: helloWorld,
}),
};
};
When you'll try to build with an import that is not part of the current directory you'll get the following error:
Build Failed
Error: NodejsNpmEsbuildBuilder:EsbuildBundle - Esbuild Failed: ✘ [ERROR] Could not resolve "../shared/hello"app.ts:2:27:
2 │ import { helloWorld } from '../shared/hello';
Custom configuration
You need to change the CodeUri property to a folder that contains all the source files that you want to share.
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: app.lambdaHandler
Thanks to this configuration you can now share your code between multiple AWS Lambda.
By default, AWS SAM CLI is using bundling, tree shaking, and minification so the code that is not called in your AWS Lambda will not be deployed.
You can look at the code directly on this sample: https://github.com/faridz974/sam-typescript
Conclusion
AWS SAM CLI with the support of Typescript is still in Beta. If you want more advanced features maybe you should not use it.
Lately, in version 1.49.0 External
and Loader
properties have been added.
If you want to share your feedback and/or requests this issue has been created.
Posted on July 8, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.