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

AWS Lambda Runtime.ImportModuleError求助:无法找到指定模块

问题:SAM部署/本地启动API时出现Runtime.ImportModuleError

问题描述

执行sam deploy或sam local start-api时,Lambda函数抛出Runtime.ImportModuleError,提示无法找到../helpers/Response模块,调整导入路径后仍未解决。

相关代码

Lambda函数代码(index.js)

const Responses = require('../helpers/Response') 

exports.handler = async( event, context, callback ) => {
    try{
        const userInputs = JSON.parse( event.body );

        return Responses._200({ msg: 'Hello world' })

    }catch(err){
        console.log( err )
        return callback( null, { msg: 'Algo salió mal | leer logs' }
        );
    };
};

待导入模块代码(helpers/Response.js)

const { HttpStatusCode } = require("./HttpStatusCode")

const headers = {
    'Content-type': 'application/json',
    'Access-Control-Allow-Methods': '*',
    'Access-Control-Allow-Origin': '*'
}
 
const Responses = {
    _200( data = {} ){
        return{
            headers,
            statusCode: HttpStatusCode.OK,
            body: JSON.stringify( data )
        }
    }
};

module.exports = Responses

错误输出

Invalid lambda response received: Invalid API Gateway Response Keys: {'errorMessage', 'trace', 'errorType'} in {'errorType': 'Runtime.ImportModuleError', 'errorMessage': "Error: Cannot find module '../helpers/Response'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/index.mjs", 'trace': ["Runtime.ImportModuleError: Error: Cannot find module '../helpers/Response'", 'Require stack:', '- /var/task/index.js', '- /var/runtime/index.mjs', ' at _loadUserApp (file:///var/runtime/index.mjs:1000:17)', ' at async Object.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']}

解决方案

1. 确认目录结构匹配导入路径

检查项目目录结构是否和导入路径对应,示例正确结构如下:

项目根目录
├── template.yaml
├── functions
│   └── your-function
│       └── index.js  # Lambda函数文件
└── helpers
    ├── Response.js
    └── HttpStatusCode.js

如果Lambda函数的index.js不在functions/your-function/这类层级,需调整require的相对路径,确保和实际文件位置一致。

2. 修正SAM模板的CodeUri配置

SAM部署时,只有CodeUri指定目录下的文件会被打包到Lambda部署包中。如果helpers目录不在Lambda函数的CodeUri路径内,会被排除在外,导致运行时找不到模块。

有两种解决方式:

  • 将helpers目录移到Lambda函数的CodeUri目录下(比如functions/your-function/helpers),然后修改导入路径为./helpers/Response
  • 将helpers封装为Lambda层,在模板中配置:
    Resources:
      HelperLayer:
        Type: AWS::Serverless::LayerVersion
        Properties:
          LayerName: helper-layer
          ContentUri: ./helpers/
          CompatibleRuntimes:
            - nodejs18.x # 替换为你的Node.js版本
      YourFunction:
        Type: AWS::Serverless::Function
        Properties:
          CodeUri: ./functions/your-function/
          Handler: index.handler
          Runtime: nodejs18.x
          Layers:
            - !Ref HelperLayer
    
    之后Lambda函数中使用require('/opt/Response')导入模块(层内容默认挂载到/opt目录)。

3. 清除本地SAM缓存

使用sam local start-api测试时,若本地路径正确但仍报错,删除项目根目录下的.aws-sam文件夹,重新执行sam build和sam local start-api,清除缓存后重试。

4. 检查文件名大小写

Lambda运行环境为Linux,对文件名大小写敏感,确认导入路径中的文件名(Response)和实际文件名完全一致,避免因大小写不匹配导致找不到模块。

5. 确认依赖完整性

若helpers模块依赖其他文件(如HttpStatusCode.js),确保这些文件存在于对应路径下;如果依赖第三方包,需确认node_modules已正确安装并被包含在部署包中。


内容的提问来源于stack exchange,提问作者David Cisneros

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:15:54