AWS Lambda NodeJS 18.x ES模块导入报错Runtime.UserCodeSyntaxError求助
问题分析与解决方案
核心错误原因
import语句位置违规:ES模块的import必须是文件的顶层语句,不能嵌套在函数(比如你的handler异步函数)或其他代码块内部,这是JavaScript ES模块语法的硬性规则,也是触发SyntaxError: Unexpected identifier的直接原因。- 导入导出语法不匹配:你的
test_module.mjs使用的是命名导出(export const test_module),但主文件里用了默认导入的语法(import test_module from ...),两者语法不兼容。
修正后的代码
主函数index.mjs
// 将import移到文件顶层,并使用命名导入匹配模块的导出 import { test_module } from "./node_modules/test_module.mjs"; export const handler = async (event) => { const result = await test_module(); // 注意:test_module是async函数,需要用await获取返回值 const response = { statusCode: 200, body: JSON.stringify(result), // Lambda返回的body需为字符串,建议序列化 }; return response; };
test_module.mjs(无需修改,确认导出方式)
export const test_module = async() => { return "Hello from module." }
Lambda ES模块额外配置注意事项
- 若项目中除了
.mjs文件还有.js文件,需在项目根目录的package.json中添加"type": "module"字段,明确告知Node.js使用ES模块规范:{ "type": "module" } - 部署Lambda时,确保
node_modules目录下的test_module.mjs被正确打包上传,也可考虑将自定义模块放在项目根目录下(而非node_modules),更便于路径管理。
内容的提问来源于stack exchange,提问作者jgood2
相关产品推荐
相关产品推荐

