aws / aws-lambda-base-images

Apache License 2.0
648 stars 107 forks source link

Need nodejs14 es6 module support #38

Open clequinio5 opened 2 years ago

clequinio5 commented 2 years ago

Entrypoint in docker still use the es5 require synthax to import module. This leads to an exception, trying to test a nodejs14 lambda with es6 module synthax.

laverdet commented 2 years ago

You can work around it by making a file: shim.js:

module.exports = require(".");

Set your handler to "shim.handler". In package.json set "main" to "./handler.mjs", and then you can export function handler(){} from handler.mjs.

huntharo commented 2 years ago

@clequinio5 - Perhaps I'm misreading your question, in which case more detail would be appreciated, but ESM / ES Modules are supported in Docker-based JavaScript Lambdas.

There are some tricks, covered in this blog post announcing ESM modules in Lambda, primarily that you need to either have a package.json with type=module in the directory of your handler (must make it into the Docker image) OR you have to use the .mjs extension. These are not AWS-isms but rather ESM-loader-isms.

I created a repo to demonstrate the entire process, including if you want to wrap an existing CommonJS application with an ESM handler for async initialization:

https://github.com/huntharo/lambda-docker-typescript-esm

Below you can see that the handler cannot access __dirname because it's an ESM module and __dirname is undefined, while the cjs-app can access __dirname becasue it's a CommonJS module (loaded from the ESM handler) can __dirname is defined in CommonJS:

image
jlarmstrongiv commented 2 years ago

@huntharo this workaround helped me due to https://github.com/aws/aws-lambda-nodejs-runtime-interface-client/issues/44#issuecomment-1032928940