TS转译Cloud Function运行失败:@google-cloud/functions-framework配置或导入问题
TypeScript云函数运行报错:
.default为undefined的问题分析与解决 问题描述
编写基础TypeScript云函数后,编译为JavaScript运行时出现报错,提示.default为undefined;手动移除代码中的.default后可正常运行,咨询该问题是导入方式错误还是TypeScript配置问题。
相关代码
TypeScript原代码
import { HttpFunction } from '@google-cloud/functions-framework' import { Request, Response } from 'express' export const testFuncHandler: HttpFunction = async (req: Request, res: Response): Promise<void> => { // 函数逻辑 }
编译后生成的错误JavaScript代码
functions_framework_1.default.http('testFuncHandler', testFuncHandler_1.testFuncHandler);
tsconfig.json配置
{ "compilerOptions": { "allowJs": true, "emitDecoratorMetadata": true, "esModuleInterop": true, "experimentalDecorators": true, "module": "commonjs", "noImplicitReturns": true, "noUnusedLocals": true, "outDir": "dist", "skipLibCheck": true, "sourceMap": true, "strict": true, "target": "es2020" }, "compileOnSave": true, "include": ["src"] }
原因分析
@google-cloud/functions-framework是CommonJS规范的模块,其导出的方法(如http)直接挂载在模块的exports对象上,并没有default导出。但你的tsconfig中开启了esModuleInterop: true,TypeScript会自动为CommonJS模块添加.default包装层,导致编译后的代码尝试访问不存在的.default属性,进而报错。
解决方案
调整导入方式,使用import * as导入整个模块,直接调用模块上的方法,避免依赖自动生成的.default:
import * as functionsFramework from '@google-cloud/functions-framework'; import { Request, Response } from 'express'; // 定义函数处理器 export const testFuncHandler: functionsFramework.HttpFunction = async (req: Request, res: Response): Promise<void> => { // 你的业务逻辑 res.status(200).send('Success'); }; // 显式注册云函数 functionsFramework.http('testFuncHandler', testFuncHandler);
编译后生成的代码会直接使用functions_framework_1.http(...),不再包含.default,即可正常运行。
内容的提问来源于stack exchange,提问作者Max Yuan
相关产品推荐
相关产品推荐

