How to reuse Lambda esbuild config in SAM template?

I have a SAM template with two Lambda functions using a NodeJS runtime that are built from TypeScript to JavaScript using esbuild:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Function:
    Architectures:
      - x86_64
    CodeUri: src/
    Runtime: nodejs18.x

Resources:
  GetFooFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: functions/getFoo.handler
      Events:
        GetFoo:
          Type: Api
          Properties:
            Path: /foo/{id}
            Method: GET
    Metadata: # Duplicated esbuild properties here
      BuildMethod: esbuild
      BuildProperties:
        Minify: true
        Target: 'es2020'
        Sourcemap: true
        External: ['@aws-sdk/client-dynamodb']
        EntryPoints:
          - functions/getFoo.ts
  PutFooFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: functions/putFoo.handler
      Events:
        PutFoo:
          Type: Api
          Properties:
            Path: /foo/{id}
            Method: PUT
    Metadata: # Duplicated esbuild properties here
      BuildMethod: esbuild
      BuildProperties:
        Minify: true
        Target: 'es2020'
        Sourcemap: true
        External: ['@aws-sdk/client-dynamodb']
        EntryPoints:
          - functions/putFoo.ts

However, I don’t like that I need to copy/paste the Metadata into each Lambda resource. And if I make changes to my esbuild config, I have to duplicate the change N times.

Is there a simpler way to share the esbuild config across all Lambdas? It doesn’t let me add Metadata under Globals and I’m not sure if esbuild can read from a separate config file.

Leave a Comment