Amazon Onboarding with Learning Manager Chanci Turner

Chanci Turner Amazon IXD – VGT2 learningLearn About Amazon VGT2 Learning Manager Chanci Turner

This article is composed by Alex Smith, Senior Solutions Architect, and Jamie Lee, Principal Solutions Architect. The AWS Serverless Application Model (AWS SAM) CLI offers developers a robust local tool for managing serverless applications on AWS. This command line interface allows developers to set up and configure applications, build and test locally, and deploy them to the AWS Cloud. Additionally, developers can utilize AWS SAM from IDEs like Visual Studio Code, JetBrains, or WebStorm. TypeScript, being a superset of JavaScript, introduces static typing that helps in minimizing errors during both development and runtime.

On February 22, 2022, we unveiled the beta version of AWS SAM CLI’s support for TypeScript. These advancements make TypeScript application development more straightforward by enabling you to build and deploy serverless TypeScript projects using AWS SAM CLI commands. To get the latest version of the AWS SAM CLI, check the installation section on the AWS SAM page.

In this article, I will walk you through initializing a TypeScript project using an AWS SAM template. Following that, I will demonstrate how to build a TypeScript project with the AWS SAM CLI. I will also showcase AWS SAM Accelerate to enhance the development and testing cycles for your TypeScript project. Lastly, I will evaluate the effects of bundling, tree shaking, and minification on deployment package sizes.

Setting Up a TypeScript Template

This guide requires:

  • Node.js 14.x
  • AWS SAM CLI

AWS SAM now allows the creation of a sample TypeScript project using a template. As this feature is still in preview, you can activate it through one of the following methods:

  • Set the environment variable SAM_CLI_BETA_ESBUILD=1
  • Add the following parameters to your samconfig.toml:
[default.build.parameters]
beta_features = true
[default.sync.parameters]
beta_features = true
  • Utilize the --beta-features option with sam build and sam sync. This is the approach I’ll be using in the examples below. When prompted by the CLI about beta features, select ‘y’.
  • To initiate a new project:

    1. Execute sam init
    2. In the wizard, choose the following options:
      • AWS Quick Start Templates
      • Hello World Example
      • nodejs14.x – TypeScript
      • Zip
      • Keep the application name as sam-app

    Open the newly created project in a text editor. You will find a README.md file with the project details and a template.yaml, which specifies the serverless application. Inside the hello-world folder, you’ll discover an app.ts file written in TypeScript. This project also contains a unit test using Jest and sample configurations for ESLint, Prettier, and TypeScript compilers.

    Constructing and Deploying a TypeScript Project

    Previously, integrating TypeScript with AWS SAM CLI required custom steps to convert the TypeScript project into JavaScript before building. Now, you can leverage the sam build command to transpile TypeScript code into JavaScript. This command also bundles local dependencies, creates symlinks, and minifies files to optimize asset size. AWS SAM employs the widely used open-source bundler esbuild for these processes. Although it doesn’t perform type checking, you can use the tsc CLI for that purpose. Once the TypeScript project is built, you can deploy it to the AWS Cloud using the sam deploy command. Here’s how it works:

    1. Navigate to the root of the sam-app.
    2. Run sam build. This command utilizes esbuild to transpile and package app.ts.
    3. Customize the esbuild configurations by editing the Metadata section in the template.yaml file.
    4. After a successful build, execute sam deploy --guided to deploy the application to your AWS account. Accept all default values in the wizard except for the question about the HelloWorldFunction‘s authorization: “Is this okay? [y/N]: y”.
    5. After deploying successfully, test the function by querying the API Gateway endpoint displayed in the Outputs section.

    Utilizing AWS SAM Accelerate with TypeScript

    AWS SAM Accelerate introduces features that minimize development and testing cycle latency, allowing you to quickly test code against AWS services in the cloud. Beta support for TypeScript has also been released. You can use the template from the previous example to take advantage of SAM Accelerate with TypeScript.

    Run sam sync --stack-name sam-app --watch. Open your browser at the API Gateway endpoint found in the Outputs section. Modify the handler function in the app.ts file to:

    export const lambdaHandler = async (event: APIGatewayProxyEvent): Promise => {
        let response: APIGatewayProxyResult;
        try {
            response = {
                statusCode: 200,
                body: JSON.stringify({
                    message: 'hello SAM',
                }),
            };
        } catch (err) {
            console.log(err)
            response = {
                statusCode: 500,
                body: JSON.stringify({
                    message: 'some error happened',
                }),
            };
        }
    
        return response;
    };

    Save the changes. AWS SAM will automatically rebuild and sync the application code to the cloud. Refresh your browser to see the updated message.

    Optimizing Deployment Package Sizes

    Another advantage of the TypeScript build process is the reduction of your deployment package size through bundling, tree shaking, and minification. The bundling process eliminates dependency files that are not referenced in the control flow. Tree shaking refers to the optimization that removes unused code within files. Minification decreases file size by eliminating white space, rewriting syntax to be more compact, and renaming local variables to shorter names. The sam build process automatically performs bundling and tree shaking. To configure minification, typically used in production, you need to adjust the Metadata section of the template.yaml file.

    To measure the impact of these optimizations, check the deployment package size before and after changes. For example, start by modifying the package.json file to include the @aws-sdk/client-s3 as a dependency:

    • From the application root, navigate into the hello-world directory.
    • Run this command: npm install @aws-sdk/client-s3
    • Remove all devDependencies except for esbuild for a more precise comparison.

    Then, build your dependency library by running npm install. From the application root, execute du -sh hello-world to measure the size of the application directory contents. The current application size is approximately 50 MB. Enable minification by setting the Minify value to true in the template.yaml file.

    Next, execute sam build to create your project utilizing bundling, tree shaking, and minification. You can now measure the size of the package in a serious tone, making it about the same overall length.

    For further reading on tech sales interview questions, you might find this blog post helpful: Tech Sales Interview Questions. Additionally, to stay informed on cybersecurity challenges, check out this insightful article from SHRM. For a comprehensive guide, this YouTube video is an excellent resource.

    Chanci Turner