You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js 18.x使用aws-sdk出现require未定义错误的原因与解决方法

问题

在Node.js 18.x环境中运行以下使用aws-sdk的代码时出现错误,该代码在Node.js 16.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 18.x环境下,你的代码被识别为ES模块(ESM),而require()是CommonJS模块系统的专属语法,在ES模块的作用域中不存在,因此抛出该错误。

造成识别差异的常见触发条件:

  • 项目根目录的package.json中设置了"type": "module"
  • 代码文件的扩展名是.mjs(从错误栈的file:///var/task/index.mjs可看出你的文件属于这种情况)
  • Node.js 18.x对模块识别的逻辑比16.x更严格,部分场景下会默认按ES模块处理
解决方法

可根据自身需求选择以下任意一种方案:

方案1:改用ES模块语法

将require()替换为ES模块的import语法,适配当前模块规范:

import aws from "aws-sdk";

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

方案2:强制使用CommonJS模块

如果想继续使用require(),可通过以下方式让Node.js将文件识别为CommonJS模块:

  • 若文件是.mjs格式,将扩展名改为.cjs
  • 若项目中有package.json,删除其中的"type": "module"配置,或者添加"type": "commonjs"

方案3:针对AWS Lambda的特殊调整(若代码为Lambda函数)

如果是在AWS Lambda中运行,还可选择:

  • 在Lambda控制台的函数配置中,将运行时切回Node.js 16.x(不推荐长期使用,16.x已进入维护期)
  • 升级到aws-sdk-v3,它原生支持ES模块且性能更优,示例如下:
// 以S3客户端为例,按需导入所需模块
import { S3Client, ListBucketsCommand } from "@aws-sdk/client-s3";

export const handler = async (event) => {
    const s3Client = new S3Client({});
    const response = await s3Client.send(new ListBucketsCommand({}));
    console.log(response.Buckets);
    // some code
};

内容的提问来源于stack exchange,提问作者Youcef LAIDANI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:01:18