- Newest
- Most votes
- Most comments
Hello.
In the current situation with CloudFormation, it automatically defaults to index.js.
I think the only way to avoid this is to package the JavaScript code, upload it to S3, and reference S3 in CloudFormation's CodeUri, as mentioned in the documentation below.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-package.html
https://docs.aws.amazon.com/lambda/latest/dg/nodejs-package.html
I found the same issue as you in the GitHub issue below, but it seems that the issue is still unaddressed as of October 2024.
https://github.com/aws-cloudformation/cloudformation-coverage-roadmap/issues/1832
The issue you're encountering is related to how AWS Lambda handles JavaScript files in Node.js environments. By default, Lambda looks for an index.js file as the entry point for Node.js functions, even when you specify index.mjs in your CloudFormation template.
To resolve this issue and ensure that your index.mjs file is used correctly, you need to make a few modifications to your CloudFormation template:
-
Change the
Handlerproperty of your Lambda function to useindex.handlerinstead ofindex.mjs. -
Add an
Environmentsection to your Lambda function properties to enable ES modules. -
Ensure your
package.jsonfile (if you're using one) includes"type": "module"to indicate that your project uses ES modules.
Here's how you can modify the CloudFormationLambdaFunction resource in your template:
CloudFormationLambdaFunction: Type: AWS::Lambda::Function Properties: Handler: index.handler Role: !GetAtt LambdaExecutionRole.Arn Runtime: nodejs18.x Code: ZipFile: | // Your Lambda function code here Timeout: 15 MemorySize: 128 Architectures: ['x86_64'] PackageType: Zip Environment: Variables: NODE_OPTIONS: "--experimental-vm-modules"
By making these changes, you're telling Lambda to use the handler function exported from the index file (which can be either .js or .mjs), and you're enabling ES module support through the NODE_OPTIONS environment variable.
Remember to include a package.json file in your deployment package with "type": "module" if you're using external dependencies or if you want to ensure ES module syntax is used.
These modifications should allow your Lambda function to correctly use the index.mjs file as intended when deployed through CloudFormation.
Sources
AWS::Lambda::Function - AWS CloudFormation
AWS Lambda template - AWS CloudFormation
Relevant content
- asked 2 years ago
- asked 2 years ago

the AI suggestion doesn't work