使用Webpack5+TypeScript构建AWS Lambda遇Runtime.HandlerNotFound错误求助
AWS Lambda 报错 Runtime.HandlerNotFound 解决建议
部署Node.js 18运行时的AWS Lambda函数,处理器配置为bundle.handler,采用TypeScript编写并通过Webpack 5编译后,测试时出现以下错误:
"errorType": "Runtime.HandlerNotFound", "errorMessage": "bundle.handler is undefined or not exported"
问题分析
从编译后的bundle.js片段可以看出,Webpack最终将导出内容包裹在了bundle对象中:
module.exports.bundle = __webpack_exports__;
而Lambda期望的是bundle.js的根导出中直接包含handler方法(即module.exports.handler),当前嵌套结构导致Lambda无法找到目标处理器。
解决方向
- 修改Webpack的library配置:移除
output.library.name,让Webpack将entry模块的导出直接挂载到module.exports上,而非嵌套在子对象中。调整后的output配置如下:
output: { filename: "[name].js", path: resolve(__dirname, "dist"), globalObject: "this", library: { type: "commonjs2", // 保留commonjs2类型,适配Node.js模块系统 }, },
- 检查TypeScript配置:确保
tsconfig.json的compilerOptions.module设置为CommonJS,保证编译后的代码与Node.js及Webpack的commonjs2输出兼容:
{ "compilerOptions": { "module": "CommonJS", "target": "ES2020", // 匹配Node.js 18的支持版本 "outDir": "./dist", "strict": true } }
- 简化Webpack entry配置:由于仅需生成一个bundle文件,可将entry简化为字符串形式,避免多入口的潜在问题:
entry: "./src/main.ts",
- 验证编译结果:重新编译后检查
bundle.js,确保最终导出结构为module.exports.handler = handler或module.exports = { handler: ... },此时Lambda即可正确识别处理器。
内容的提问来源于stack exchange,提问作者flambo
相关产品推荐
相关产品推荐

