我在 AWS Lambda 上使用 NodeJs(ES6),并将 node_module 作为 AWS 层,并且我想在 SNS 上发布消息。
上面的代码与 CommonJs 语法完美配合,但使用导入语法(ES6)会遇到 aws-sdk/sns-client 的问题,因为这是 commonsJS 模块。
包.json
"name": "test",
"version": "1.0.0",
"dependencies": {
"@aws-sdk/client-sns": "^3.370.0",
},
"type": "module",
}
错误
2024-05-05T20:50:31.064Z undefined ERROR Uncaught Exception
{
"errorType": "Runtime.UserCodeSyntaxError",
"errorMessage": "SyntaxError: Named export 'AWS' not found. The requested module 'aws-sdk' is a CommonJS module, which may not support all module.exports as named exports.\nCommonJS modules can always be imported via the default export, for example using:\n\nimport pkg from 'aws-sdk';\nconst { AWS } = pkg;\n",
"stack": [
"Runtime.UserCodeSyntaxError: SyntaxError: Named export 'AWS' not found. The requested module 'aws-sdk' is a CommonJS module, which may not support all module.exports as named exports.",
"CommonJS modules can always be imported via the default export, for example using:",
"",
"import pkg from 'aws-sdk';",
"const { AWS } = pkg;",
"",
" at _loadUserApp (file:///var/runtime/index.mjs:1084: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"
]
}
也尝试过以下,
import pkg from 'aws-sdk';
const { AWS } = pkg;
提前谢谢您。
您当前包含 SNS v3 版本:
"dependencies": {
"@aws-sdk/client-sns": "^3.370.0",
},
但是你使用的就像是 v2 包一样:
import pkg from 'aws-sdk';
const { AWS } = pkg;
所以要么你需要包含 v2 版本的 aws-sdk (不是一个好主意)
或者你需要像 v3 包一样使用它:
import { SNSClient } from "@aws-sdk/client-sns";
...
const client = new SNSClient({});
您可以在此处查看 v3 的示例:https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/javascript_sns_code_examples.html