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.
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
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
})
}
}
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'
lodash-es
as an ESM-compatible dependencynpm install -g serverless
) or open serverless (npm install -g oss-serverless
)npm install
serverless deploy
serverless invoke --function hello
severless remove
Thats about it. Nothing too fancy.
The code for this is in serverless-esm-functions-no-build-example repo.
Enjoy and happy coding.