为Firebase云函数配置TypeScript tsconfig.json以支持ES模块
解决Firebase云函数TypeScript环境下ES模块报错问题
问题现象
使用ES模块(import/export)的Firebase云函数在JavaScript环境正常运行,但TypeScript环境报错:
SyntaxError: Cannot use import statement outside a module
index.ts未被识别为ES模块,重命名为index.mts也无效,推测是tsconfig.json或package.json配置问题。
解决方案
1. 修正tsconfig.json的输出目录与模块解析配置
当前outDir设置为src,会导致编译后的JS文件与TS源文件混存,且模块解析规则适配性不足。修改如下:
{ "compilerOptions": { "module": "ESNext", "moduleResolution": "NodeNext", // 适配ES模块的解析规则 "noImplicitReturns": true, "noUnusedLocals": true, "outDir": "dist", // 独立目录存放编译产物 "sourceMap": true, "strict": true, "target": "ESNext" }, "compileOnSave": true, "include": ["src/index.ts"], "exclude": ["wwwroot", "dist"] // 排除编译输出目录 }
2. 更新package.json的入口文件指向
main字段必须指向编译后的JS文件,而非TS源文件,确保Firebase加载正确的运行产物:
{ "name": "functions", "type": "module", "scripts": { "build": "tsc", "build:watch": "tsc --watch", "serve": "npm run build && firebase emulators:start --only functions", "shell": "npm run build && firebase functions:shell", "start": "npm run shell", "deploy": "npm run build && firebase deploy --only functions", "logs": "firebase functions:log" }, "engines": { "node": "16" }, "main": "dist/index.js", // 指向编译后的ES模块文件 "dependencies": { "firebase-admin": "^11.2.0", "firebase-functions": "^4.0.1" }, "devDependencies": { "typescript": "^4.8.4" }, "private": true }
3. 清理旧产物并重新编译
删除src目录下残留的JS文件(若之前编译到该目录),执行npm run build生成全新的编译产物到dist目录。
4. 验证编译产物
检查dist/index.js内容,确认代码保留了import/export语法,而非被转换为CommonJS的require/exports。
测试步骤
- 执行
npm run build确认dist目录生成正确产物。 - 运行
npm run serve启动模拟器,测试云函数是否正常触发与执行。
内容的提问来源于stack exchange,提问作者Thomas David Kehoe
相关产品推荐
相关产品推荐

