最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin43浏览0评论

"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" 使用 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
.

这个错误的原因是什么,我们如何避免它。

回答如下:

Node18 for Lambda 使用 JavaScript SDK V3 .

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

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

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

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


SDK V2

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

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

SDK V3

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

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

向后 V2 兼容风格

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

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

来源

发布评论

评论列表(0)

  1. 暂无评论