如何通过SAM转译并打包含依赖的AWS Lambda TypeScript函数?
解决方案:TypeScript AWS Lambda 构建缺失依赖与工具文件问题
问题根源
- tsconfig 配置错误:
noEmit: true会阻止TypeScript编译器生成JS文件,SAM仅能自动转译单独的handler.ts,无法处理依赖的helper.ts。 - Handler路径配置不当:template.yaml中指定的
src/handler.Handle指向源码路径,但构建产物中不存在src目录,导致运行时找不到入口。 - 未配置完整构建逻辑:默认SAM构建未明确处理TypeScript项目的依赖安装与全量源码转译,导致
node_modules和工具文件被遗漏。
分步修复
1. 修正tsconfig.json
将noEmit改为false,并指定输出目录,确保所有TypeScript文件都能被转译:
{ "compilerOptions": { "target": "es2020", "strict": true, "preserveConstEnums": true, "noEmit": false, "outDir": "./dist", "sourceMap": false, "module": "commonjs", "moduleResolution": "node", "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "isolatedModules": true }, "exclude": ["node_modules", "**/*.test.ts"] }
2. 调整template.yaml配置
推荐使用esbuild构建(SAM原生支持,高效自动处理依赖与转译),修改函数配置如下:
handlerFunction: Type: AWS::Serverless::Function Properties: Handler: handler.Handle Runtime: nodejs20.x # 匹配你的Node.js版本 CodeUri: src/ Metadata: BuildMethod: esbuild BuildProperties: Minify: true Target: es2020 Sourcemap: false EntryPoints: - handler.ts
如果习惯用自定义构建命令,可改用以下配置:
handlerFunction: Type: AWS::Serverless::Function Properties: Handler: dist/handler.Handle Runtime: nodejs20.x CodeUri: . Metadata: BuildMethod: makefile
同时在项目根目录创建Makefile:
build-handlerFunction: npm install --production tsc
3. 验证构建结果
执行sam build后,检查build/handlerFunction目录:
- 应包含转译后的
handler.js、utils/helper.js - 应包含生产依赖的
node_modules目录
额外提示
- 确保
package.json中dependencies只保留运行时必需包,devDependencies存放typescript、@types/aws-lambda等开发工具,SAM会自动排除dev依赖。 - 使用esbuild时无需手动执行
tsc,esbuild会直接读取tsconfig配置并完成转译打包。
内容的提问来源于stack exchange,提问作者kes92
相关产品推荐
相关产品推荐

