I'm using the modern import/export syntax in my NodeJS functions for the Serverless Framework.
After deployment, when I try and invoke the URL I see HTTP 502 {"message": "Internal server error"}
error. The CloudWatch logs say:
require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
When I inspect the code through the AWS Console > Lambda, I can see the Serverless Framework has generated a s_getDns.js
file for my function, and inside it's using the legacy "require" syntax:
var serverlessSDK = require('./serverless_sdk/index.js');
serverlessSDK = new serverlessSDK({
// ...
});
I'm using v3.23.0 of the Serverless Framework.
I have tried:
(which lead to the error described above)
I have also tried manually editing the s_getDns.js
file in the Lambda console to use the new import/export syntax, however I then start getting errors from the serverless_sdk/index.js
file (which is minified, so I haven't been able to refactor that one).
This issue comment suggests that both AWS and the Serverless Framework now support ESM out of the box. I'm not sure why it's not working in my case.
What is the issue, or what can I do to troubleshoot this further?
It looks like you're using Serverless Dashboard plugin in your application (you have app
and org
defined in your config file) and at the moment, ESM modules are not supported by that integration: https://github.com/serverless/serverless/issues/11424#issuecomment-1266584167
You have several options: