繁体   English   中英

"errorMessage": "require is not defined in ES module scope, you can use import instead" 使用 Node.js 18.x 时

[英]"errorMessage": "require is not defined in ES module scope, you can use import instead" When using Node.js 18.x

当我使用aws-sdk模块 Node.js 18.x 时:

const aws = require("aws-sdk");

exports.handler = async (event) => {
    console.log('Hello!');
    // some code
};

我收到此错误:

{
  "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"
  ]
}

相同的代码适用于较晚的版本,例如Node.js 16.x

出现这个错误的原因是什么,又该如何避免呢。

Lambda 的 Node18 使用 JavaScript SDK V3。

AWS SDK for Javascript v2 发布了一个支持所有 AWS 服务的 npm 包。 这使得在仅使用少数服务或操作时以大量依赖为代价在项目中使用多个服务变得容易。

在移动设备等资源受限的环境中,为每个服务客户端提供单独的包可以优化依赖性。 适用于 Javascript v3 的 AWS 开发工具包提供了此类模块化程序包。 我们还拆分了 SDK 的核心部分,以便服务客户只提取他们需要的部分。 例如,以 JSON 格式发送响应的服务将不再需要将 XML 解析器作为依赖项。

因为你只导入你需要的模块,你可以像下面那样做:

const { S3 } = require("@aws-sdk/client-s3");


开发工具包V2

const AWS = require("aws-sdk");

const s3Client = new AWS.S3({});
await s3Client.createBucket(params).promise();

开发工具包V3

const { S3 } = require("@aws-sdk/client-s3");

const s3Client = new S3({});
await s3Client.createBucket(params)

事实上,正如@Lee Hannigan 所说,“Lambda 的 Node18 使用 JavaScript SDK V3”

您还可以使用亚马逊文档中描述的 v2 兼容样式:

import * as AWS from "@aws-sdk/client-s3";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM