My Firebase Cloud Functions utilize ES modules (import and export) in JavaScript but encounter issues when written in TypeScript. An error message stating "SyntaxError: Cannot use import statement outside a module" appears. The problem seems to stem from the fact that my index.ts file is not recognized as an ES module, while its identical counterpart index.js is acknowledged as such. Renaming it to index.mts did not resolve the issue, indicating a potential misconfiguration in tsconfig.json.
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "node",
"noImplicitReturns": true,
"noUnusedLocals": true,
"outDir": "src",
"sourceMap": true,
"strict": true,
"target": "ESNext"
},
"compileOnSave": true,
"include": [
"src/index.ts"
],
"exclude": ["wwwroot"],
}
Displayed below is my package.json:
{
"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": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "16"
},
"main": "src/index.ts", // change to "src/index.js" for JavaScript
"dependencies": {
"firebase-admin": "^11.2.0",
"firebase-functions": "^4.0.1"
},
"devDependencies": {
"typescript": "^4.8.4"
},
"private": true
}
Additionally, provided are the Firebase Cloud Functions defined within my index.ts:
import * as functions from "firebase-functions";
export default function helloWorld() {
console.log("Hello, world!");
};
export const makeUppercase = functions.firestore.document('messages/{docId}').onCreate((snap: any, context: any) => {
const original = snap.data().original;
functions.logger.log('Uppercasing', context.params.docId, original);
const uppercase = original.toUpperCase();
return snap.ref.set({ uppercase }, { merge: true });
});