通过Serverless.com部署node20 AWS Lambda函数将模块导入设置为ESM

ryhaxcpt  于 5个月前  发布在  Node.js
关注(0)|答案(1)|浏览(62)

我们正在使用Serverless.com将Lambda函数部署到AWS,并已开始将一些较旧的函数升级到node 20。

provider:
  name: aws
  runtime: nodejs20.x

functions:
  routeInvoice:
    handler: src/functions/routeInvoice/routeInvoice.handler

字符串
有一个文件src/functions/routeInvoice/routeInvoice.js,它具有导出的函数:

const handler = async (event, context) => {
  console.log('event:', JSON.stringify(event), JSON.stringify(context));

  try {
    return await routeInvoice(event);
  } catch (err) {
    console.error('routeInvoice handler error:', err);
    throw err;
  }
};

module.exports = { handler };


在deploy之后,我们得到错误:

{
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module 'handler'\nRequire stack:\n- /var/runtime/index.mjs",
    "stack": [
        "Runtime.ImportModuleError: Error: Cannot find module 'handler'",
        "Require stack:",
        "- /var/runtime/index.mjs",
        "    at _loadUserApp (file:///var/runtime/index.mjs:1087:17)",
        "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)",
        "    at async start (file:///var/runtime/index.mjs:1282:23)",
        "    at async file:///var/runtime/index.mjs:1288:1"
    ]
}


package.json没有任何type属性,根据AWS文档,文件扩展名.js应该被视为Common JS而不是ESM。
使用sls invoke local -f routeInvoice...在本地执行函数可以正常工作!
我错过了什么?

bwleehnv

bwleehnv1#

我们在同一个Serverless.yml中同时拥有Java Lambda和Node.js Lambda,而且在SLS v2和现在的v3之间,打包的工作方式似乎有所不同。
我把package: artifact移到了Java函数中,这样Java代码就不会出现在Node.js Lambda ZIP中,现在它工作得很好!
显然,当Node.js Lambda中有Java代码时,AWS会感到困惑,然后似乎默认为ESM。

相关问题