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

使用SAM CLI构建Lambda项目时输出CJS而非MJS,引发顶层await报错

解决SAM CLI构建TypeScript Lambda时顶层await报错问题

问题描述

使用SAM CLI构建TypeScript+ES2022的Lambda项目时,期望输出MJS文件,但实际生成CJS格式,触发报错:

Build Failed
Error: NodejsNpmEsbuildBuilder:EsbuildBundle - Esbuild Failed: ✘ [ERROR] Top-level await is currently not supported with the "cjs" output format

项目现有关键配置:

  • package.json 已声明 "type": "module"
  • tsconfig.json 配置了 "module": "nodenext"、"target": "es2022"
  • template.yaml 使用esbuild作为构建方法,但未指定输出格式

解决方案

在template.yaml的BuildProperties中添加Format: esm,强制esbuild输出ES模块(MJS)格式:

修改后的template.yaml相关片段:

......
Metadata:
  BuildMethod: esbuild
  BuildProperties:
    Target: "es2022"
    Minify: false
    Sourcemap: true
    EntryPoints:
      - src/handlers/app.ts
    Format: esm

说明

SAM的esbuild构建器默认不会自动读取package.json中的type: module配置,显式指定Format: esm后,esbuild会生成支持顶层await的MJS文件,解决格式不兼容的问题。

重新执行sam build即可完成正常构建。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:10:09