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

AWS Serverless项目替换Webpack为Esbuild后出现Cannot read property 'name'错误

AWS Serverless切换Esbuild后出现Cannot read property 'name' of undefined错误排查

近期在AWS Serverless项目中将Webpack替换为Esbuild,原Webpack环境下运行正常,切换后出现以下错误:

× Unhandled exception in handler 'getNotification'.
× Cannot read property 'name' of undefined
× TypeError: Cannot read property 'name' of undefined
at ...\.esbuild\.build\src\functions\api\index.js:21033:22
      at __decorateClass (...\.esbuild\.build\src\functions\api\index.js:32:24)
      at Object.<anonymous> (...\.esbuild\.build\src\functions\api\index.js:703945:1)
      at Module._compile (internal/modules/cjs/loader.js:1085:14)
      at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
      at Module.load (internal/modules/cjs/loader.js:950:32)
      at Function.Module._load (internal/modules/cjs/loader.js:790:12)
      at Module.require (internal/modules/cjs/loader.js:974:19)
      at require (internal/modules/cjs/helpers.js:101:18)
      at _tryRequireFile (...\node_modules\serverless-offline\src\lambda\handler-runner\in-process-runner\aws-lambda-ric\UserFunction.js:209:35)

Serverless.yaml配置

plugins:
  - serverless-dotenv-plugin
  - serverless-offline-ssm
  - serverless-layers
  - serverless-scriptable-plugin
  - serverless-esbuild
  - serverless-offline
   ...

esbuild:
    bundle: true
    minify: false

相关依赖版本

  • serverless: ^3.22.0
  • serverless-esbuild: ^1.32.8
  • serverless-offline: ^9.3.1
  • esbuild: ^0.15.7

错误原因及解决办法

核心原因

错误触发点在__decorateClass函数,说明Esbuild对装饰器的编译逻辑和Webpack存在差异,导致类装饰器处理时出现未定义引用。常见场景包括装饰器语法支持不足、打包配置缺失关键参数、依赖版本兼容问题。

解决步骤

  1. 完善Esbuild打包配置
    在serverless.yaml的esbuild节点补充必要参数,确保语法转换匹配Lambda运行时:

    esbuild:
      bundle: true
      minify: false
      target: "node16" # 替换为你的Lambda实际运行时版本(如node14/node18)
      sourcemap: true # 生成源码映射,方便定位具体错误代码
      tsconfig: "./tsconfig.json" # 若使用TypeScript,指定配置文件路径
    
  2. 确认TypeScript装饰器配置(若项目用TS)
    检查tsconfig.json中是否开启装饰器支持:

    {
      "compilerOptions": {
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
      }
    }
    
  3. 升级依赖版本
    当前使用的esbuild 0.15.x和serverless-esbuild 1.32.8均为较旧版本,存在不少装饰器相关bug,建议升级到最新稳定版:

    npm update esbuild serverless-esbuild
    
  4. 排查第三方依赖问题
    若项目中使用了带装饰器的第三方包,可尝试将其排除在Esbuild打包范围外,通过external配置声明:

    esbuild:
      # ...其他配置
      external:
        - "第三方依赖包名"
    
  5. 定位具体错误代码
    利用sourcemap找到编译后代码对应的原始源码位置,查看触发错误的类装饰器逻辑,针对性调整代码或装饰器使用方式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:45:25