YCF*_*F_L 15 amazon-web-services node.js aws-sdk aws-lambda
当我使用aws-sdkNode.js 18.x 模块时:
const aws = require("aws-sdk");
exports.handler = async (event) => {
console.log('Hello!');
// some code
};
Run Code Online (Sandbox Code Playgroud)
我收到这个错误:
{
"errorType": "ReferenceError",
"errorMessage": "require is not defined in ES module scope, you can use import instead",
"trace": [
"ReferenceError: require is not defined in ES module scope, you can use import instead",
" at file:///var/task/index.mjs:1:13",
" at ModuleJob.run (node:internal/modules/esm/module_job:193:25)",
" at async Promise.all (index 0)",
" at async ESMLoader.import (node:internal/modules/esm/loader:530:24)",
" at async _tryAwaitImport (file:///var/runtime/index.mjs:921:16)",
" at async _tryRequire (file:///var/runtime/index.mjs:970:86)",
" at async _loadUserApp (file:///var/runtime/index.mjs:994:16)",
" at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1035:21)",
" at async start (file:///var/runtime/index.mjs:1200:23)",
" at async file:///var/runtime/index.mjs:1206:1"
]
}
Run Code Online (Sandbox Code Playgroud)
例如,相同的代码适用于最新版本Node.js 16.x。
这个错误的原因是什么,我们如何避免它。
lee*_*gan 11
Node18 for Lambda 使用 JavaScript SDK V3 。
AWS SDK for Javascript v2 发布了一个支持所有 AWS 服务的 npm 包。这使得在项目中使用多个服务变得很容易,但在仅使用少数服务或操作时会产生较大的依赖关系。
在移动设备等资源受限的环境中,为每个服务客户端提供单独的包可以优化依赖性。AWS SDK for Javascript v3 提供了此类模块化包。我们还拆分了 SDK 的核心部分,以便服务客户端只提取他们需要的内容。例如,以 JSON 格式发送响应的服务将不再需要 XML 解析器作为依赖项。
由于您只导入所需的模块,因此可以如下操作:
const { S3 } = require("@aws-sdk/client-s3");
const AWS = require("aws-sdk");
const s3Client = new AWS.S3({});
await s3Client.createBucket(params).promise();
Run Code Online (Sandbox Code Playgroud)
const { S3 } = require("@aws-sdk/client-s3");
const s3Client = new S3({});
await s3Client.createBucket(params)
Run Code Online (Sandbox Code Playgroud)
import * as AWS from "@aws-sdk/client-s3";
const s3Client = new AWS.S3({});
await s3Client.createBucket(params);
Run Code Online (Sandbox Code Playgroud)
Lambda index.js 现在的扩展名为.mjs. 重命名有时可以解决您遇到的任何问题。
| 归档时间: |
|
| 查看次数: |
28206 次 |
| 最近记录: |