执行sls offline start时AppSync Simulator报TypeError错误
注:原始提问内容为机器翻译,如有表述不当敬请谅解
问题描述
- 基于Serverless Framework搭建AppSync本地离线开发环境,使用的插件包括
serverless-dynamodb-local、serverless-appsync-simulator、serverless-offline - 安装插件后执行
sls offline start命令抛出如下错误:
AppSync Simulator: TypeError: Cannot convert undefined or null to object
- 项目未采用yml编写配置,使用TypeScript编写配置文件,现有配置片段如下:
//appsync simulator config "appsync-simulator": { location: ".esbuild/.build", watch: false, }, //dynamodb local config dynamodb: { stages: "dev", start : { port: 8000, inMemory: true, // migrate: true, // seed: true, } }, //esbuild config esbuild: { bundle: true, minify: false, sourcemap: true, exclude: ["aws-sdk"], target: "node14", define: { "require.resolve": undefined }, platform: "node", concurrency: 10, },
schema.graphql文件存放在项目根目录,项目部署到AWS管理控制台可正常运行,需搭建本地离线调试环境供团队开发使用。
解决方案
该报错是serverless-appsync-simulator启动时读取必填配置项拿到空值导致,按以下顺序排查修复即可:
- 补全顶层
appsync必填配置块
你当前仅配置了appsync-simulator模拟器的运行参数,缺失插件强制要求的顶层appsync核心配置:模拟器不会自动扫描读取根目录的schema文件,没有该配置块时插件读取配置会拿到undefined,直接触发类型错误。
补全最小可用配置如下(字段和你线上控制台的配置对齐即可):appsync: { name: "your-appsync-api-name", schema: "schema.graphql", // 显式声明根目录schema文件路径 authenticationType: "API_KEY", // 替换为你线上实际使用的认证方式 apiKeys: [{ name: "localDevKey", expires: 365 }], dataSources: [ // 补全dynamodb数据源配置,和线上配置保持一致 ], mappingTemplates: [ // 补全对应解析器的映射模板配置 ] }, "appsync-simulator": { location: ".esbuild/.build", watch: false, }, - 调整插件加载顺序
检查配置文件中的plugins数组,必须保证serverless-appsync-simulator在serverless-offline之前加载,错误的加载顺序会导致模拟器无法正确引用其他插件的实例配置,正确顺序参考:plugins: [ "serverless-dynamodb-local", "serverless-appsync-simulator", "serverless-esbuild", "serverless-offline" ] - 移除esbuild冲突配置
现有esbuild配置中define: { "require.resolve": undefined }会覆盖Node.js原生的路径解析逻辑,导致appsync模拟器动态加载编译后的解析器文件时拿到空路径,直接删除该行配置即可。 - 修正dynamodb本地配置格式
dynamodb配置中的stages字段要求传入数组格式,将现有stages: "dev"修改为stages: ["dev"],字符串格式会导致插件匹配运行阶段时返回空值。
所有配置修改完成后,先执行sls package确认配置可正常编译,再执行sls offline start即可正常启动本地调试环境。
内容的提问来源于stack exchange,提问作者account web
相关产品推荐
相关产品推荐

