Dismiss
  • Scroll up
  • Toggle Theme
  • View as Mobile

Using unbundled ESM in AWS Lambda Functions

ESM modules are finally gaining support for CJS. This means npm packages that use require will work in ESM land. Hooray 🎉.

I've used bundling with esBuild in the past with AWS Lambda. I didn't love the build step and how many npm packages wouldn't work in pure ESM land so I put it on the shelf.

But... now you can just deploy your ESM code, and things just work™, it's high time we start migrating older CJS code to ESM.

Let's jump into it.

This is a simple example demonstrating how to use ES Modules (ESM) with the Serverless Framework without requiring a build step.

Why no bundle?

  1. Bundling can mess with logging unless you setup sourcemaps.
  2. It's super simple
  3. You can read un-minified/compiled code in AWS console if you need to.

How it works

You simply need to set "type": "module" in your package.json

Then the serverless framework will package and deploy your unbundled ESM lambda function

This example repo demonstrates how to uses lodash-es as a direct dependency

Our lambda code

This is our lambda handler.

import { capitalize, reverse } from 'lodash-es'

export const handler = async (event) => {
  const message = 'hello world'
  const processedMessage = capitalize(message)
  const reversedMessage = reverse(message.split('')).join('')
  
  return {
    statusCode: 200,
    body: JSON.stringify({
      original: message,
      capitalized: processedMessage,
      reversed: reversedMessage
    })
  }
}

Our config

Below is a simple serverless.yml file with our runtime defined and a pointer to where our code lives in ./my-function.js.

service: my-esm-service

provider:
  name: aws
  runtime: nodejs22.x

functions:
  hello:
    handler: my-function.handler

# Optionally, you can exclude files from the packaged zip
package:
  patterns:
    - '!.gitignore'
    - '!.DS_Store'
    - '!README.md'

Features

  • Native ES Module support using Node.js 22.x
  • Uses lodash-es as an ESM-compatible dependency
  • No bundling or transpilation required
  • Simple Lambda function that processes text

Prerequisites

  • Node.js 22.x or later
  • Serverless Framework CLI installed (npm install -g serverless) or open serverless (npm install -g oss-serverless)
  • AWS credentials configured

Installation

  1. Clone the repository
  2. Install dependencies:
npm install

Usage

  1. Deploy the function:
serverless deploy
  1. Invoke the function:
serverless invoke --function hello
  1. Teardown
severless remove

Wrapping up

Thats about it. Nothing too fancy.

The code for this is in serverless-esm-functions-no-build-example repo.

Enjoy and happy coding.