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

AWS SAM Node.js TypeScript模板本地运行报错求助

解决方案:AWS SAM TypeScript模板本地运行找不到'app'模块

问题根源

TypeScript模板本地运行时SAM无法正确加载构建后的模块,核心原因是构建产物路径不匹配或M1 Mac的Docker架构适配问题,而部署到AWS正常是因为云端环境自动适配了架构与路径映射。

具体修复步骤

1. 确认模板中CodeUri路径正确

检查template.yaml里的函数配置,确保CodeUri指向TypeScript编译后的dist目录:

HelloWorldFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: hello-world/dist/
    Handler: app.lambdaHandler
    Runtime: nodejs16.x

执行sam build后,查看.aws-sam/build/HelloWorldFunction目录,确认存在app.js(或app.mjs)文件。

2. 适配M1 Mac的Docker架构

M1芯片为arm64架构,SAM默认使用x86_64镜像会导致文件加载异常,需指定arm64平台:

  • 临时启动命令:
    sam local start-api --platform linux/arm64
    
  • 永久配置(修改samconfig.toml):
    [default.local.start-api.parameters]
    platform = "linux/arm64"
    

3. 清理缓存并重新构建

旧的构建缓存可能导致产物异常,执行以下命令清理后重新构建:

rm -rf .aws-sam hello-world/dist
sam build

4. 验证TypeScript编译配置

打开hello-world/tsconfig.json,确认编译输出目录和源码目录配置正确:

{
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src",
    "target": "ES2020",
    "module": "commonjs",
    "strict": true
  },
  "include": ["src/**/*"]
}

手动在hello-world目录执行npm run build,确认dist目录生成app.js文件。

验证

完成以上步骤后,重新执行sam local start-api --platform linux/arm64,访问http://127.0.0.1:3000/hello即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:12:30