I have a library foo which is written with ES6, import/export and in Typescript.
I have an app bar which uses foo. bar is also written with exports and Typescript. I would like to get bar running on AWS Lambda.
From what I can tell, I cannot use import/export in Lambda (with runtime node 14.x) as
export const handler = async () => {...};
Will error, but
exports.handler = async () => {...};
Will not.
So within my tsconfig I have set:
"target": "ES5", (or ES6)
"module": "CommonJS",
under the compiler options.
With this, running on Lambda I get errors since it now tries to require the foo library and says it must use import.
How can I achieve my end goal?
As I see it there are 3 options, none of which I know much about since I am still new to the JS nuances.
bar app transpile, or use webpack, or whatever the tool may be to replicate import in cjs.foo library also include a CJS distrobution (started doing this and got many errors from the hoops I had to get through to make the library work in es6).ES modules support was added in Node v14. However, we need to help Node a bit in determining which type he has to use to load a file.
If you're only using ES modules, it's quite easy, you can just add "type": "module" to your package.json file in order to tell Node to use ES modules. Another way is to use a different file extension. However, since AWS Lambda needs the handler to be configured in the form of filename.methodname, it will always use the .js extension, which makes it not possible to use a different file extension for your entry point.
I have tested the "type": "module" in AWS Lambda, and this seems to work. I have not tested how interoperability would work with dependencies that use CommonJS modules, but I assume this would work out of the box.
You can refer to this blog for more information on how Node handles this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With