The compilation of TypeScript and ES Modules is not supported in Firebase Functions

Recently, I integrated Firebase Functions into my project with the default settings, except for changing the value "main": "src/index.ts" in the package.json file because the default path was incorrect.

Here is the code that was working:

// index.ts

const { initializeApp } = require('firebase-admin/app');
const { onValueCreated } = require('firebase-functions/v2/database');
const { logger } = require('firebase-functions');

initializeApp();

exports.testFn = onValueCreated(
  '/users/{uid}/company/accounts/{accId}',
  (event) => {
    logger.log(event);
  }
);

However, after making changes to switch from require to ESM imports and adding a type to an event parameter, the following error occured:

// index.ts

// Switched imports from require to ESM
import { initializeApp } from 'firebase-admin/app';
import { onValueCreated } from 'firebase-functions/v2/database';
import { logger } from 'firebase-functions';

initializeApp();

exports.testFn = onValueCreated(
  '/users/{uid}/company/accounts/{accId}',
  (event: any) => { // Added ': any' type to event parameter to avoid .ts error
    logger.log(event);
  }
);

The error message received is:

shutdown requested via /__/quitquitquit

!!  functions: Failed to load function definition from source: FirebaseError: Functions codebase could not be analyzed successfully. It may have a syntax or runtime error

Upon investigation, it was found that both introducing ES Modules import and using types were causing this error. The presence of typescript in package.json did not resolve the issue. Additionally, appending a file extension (like .js or .ts) to the end of an ESM import did not help either.

Answer №1

I successfully found a solution to my question. It may not be perfect, but it gets the job done.

Correction in Command

Initially, I was using the firebase emulators:start command, which turned out to be incorrect.

After examining the CLI Firebase Functions project, I discovered that there are specific commands within the package.json:

    "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"

The correct command to use is npm run serve. Additionally, ensure that

"main": "lib/index.js"
remains intact in package.json. This setup will compile TypeScript code into JavaScript and place it in lib/index.js, enabling our application to utilize both ES Modules and TypeScript.

Compiling Issue

Despite having "compileOnSave": true configured in tsconfig.json, I encountered difficulties with triggering recompilation upon saving. My current workaround involves keeping a second terminal open and executing npm run build whenever recompilation is necessary.

If a solution to this issue is discovered by me or anyone else, I will update this post.

Expanding Emulation Services in Firebase Emulator

To emulate all required Firebase services locally, I removed --only functions from the serve command in package.json.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble debugging the current TypeScript file in VS Code because the corresponding JavaScript file is missing

In my current project using Visual Studio Code version 1.17, I am focusing on debugging the current typescript file. As part of my setup, I have a build task in place which generates a corresponding javascript file structure like so: src/folder1/folder2/m ...

Encountered an issue with Webpack 5 - A ReferenceError was thrown: require is not recognized

I encountered an error while attempting to access the main page of my app in the browser: Uncaught ReferenceError: require is not defined at Object.events (main.bundle.js:90508:1) at __webpack_require__ (main.bundle.js:91217:33) at fn (main.bundle.js:91451 ...

Navbar Growth Effect

I'm attempting to create an expanding effect in my navbar using Angular. When I click on "show information," the content should slide up. The issue is that the top part of my footer does not follow the effect. I have tried something like: <foot ...

Exploring TypeScript: Optional Sub-Properties

I've been exploring ways to create a type-alias with properties like "answer" that I came across in this post by another user (Typescript interface optional properties depending on other property). Here's an example: type Sample = { key1: true, ...

Struggles with updating app.component.ts in both @angular/router and nativescript-angular/router versions

I have been attempting to update my NativeScript application, and I am facing challenges with the new routing system introduced in the latest Angular upgrade. In my package.json file, my dependency was: "@angular/router": "3.0.0-beta.2" After the upg ...

Angular - Enabling the next screen button only after completing multiple selections

Currently, I'm working on a screen where users can select multiple options from a table. The requirement is that they must select at least 3 options before they can proceed. However, I am facing difficulties in implementing this functionality and unsu ...

How to minimize scaffolding with Redux, React, and Typescript?

Is there a way to avoid the process of instrumenting my Redux-Aware components? The level of scaffolding required seems excessive. Take, for instance, the minimal code necessary to define a redux-aware component: class _MyActualComponent extends React.Co ...

The FileReader's onload event handler does not seem to be triggering as expected

In short, my issue revolves around reading a csv file from an android device using JavaScript's FileReader. Although my code was functioning properly a month ago, upon revisiting it recently I discovered that the onload function no longer seems to be ...

What's the process for deducing the default generic parameter from a function type?

Is there a way to extract the default type parameter of a function in order to make this statement compile successfully? const fails: string = "" as ReturnType<<T = string>() => T>; ...

When I run the app on my iPad3, I am receiving a nil value for a variable that I do not get when running the

My first app has a function that posts to Firebase as a dictionary with string values. When I retrieve the same data in my second app, two of the values appear to be integers instead of strings. To fix this issue, I convert those values to integers which w ...

Design buttons that are generated dynamically to match the style

I have a challenge in styling dynamically generated buttons. I've developed a component responsible for generating these dynamic buttons. const TIMER_PRESETS: Record<string, number> = { FIFTHTEENSEC: 15, THIRTYSEC: 30, FORTYFIVESEC: 45, ...

Is it possible to achieve real-time two-way data binding in a reactive form by passing values from one formgroup to another formgroup? If so, how

There are 2 FormGroups named orderForm and parcelForm on a page. The parcelForm is generated dynamically within a FormArray. In the parcelForm, there are FormControls like net_weight and gross_weight, while the OrderForm has FormControls such as total_net_ ...

What steps should I take to fix the SyntaxError occurring with the unexpected token 'export' in a React Next.js project?

Currently working on a React Next.js project and I've come across an unexpected SyntaxError: Unexpected token 'export' issue. I've reviewed the solutions provided here, but I'm having trouble grasping how to correctly implement th ...

Utilize @db.Decimal within the Prisma framework for the parameters "s", "e", and "d"

When I define the schema in Prisma like this: value Decimal? @db.Decimal(7, 4) Why do I always get this format when retrieving the value from the database: "value": { "s": 1, "e": 0, & ...

A single element containing two duplicates of identical services

I am encountering an issue with my query builder service in a component where I need to use it twice. Despite trying to inject the service twice, it seems that they just reference each other instead of functioning independently, as shown below: @Component( ...

Struggling to Enforce Restricted Imports in TypeScript Project Even After Setting baseUrl and resolve Configuration

I am facing challenges enforcing restricted imports in my TypeScript project using ESLint. The configuration seems to be causing issues for me. I have configured the baseUrl in my tsconfig.json file as "src" and attempted to use modules in my ESLint setup ...

Struggling to comprehend the intricacies of these generic declarations, particularly when it comes to Type Argument Lists

I'm currently reviewing the code snippet from the TypeScript definitions of fastify. I am struggling to understand these definitions. Although I am familiar with angle brackets used for generics, most TypeScript tutorials focus on simple types like Ar ...

Only include unique objects in the array based on a common property

I am currently working with the following array: [ {name: "Mike", code: "ABC123"}, {name: "Sarah", code: "DEF456"}, {name: "John", code: "GHI789"}, {name: "Jane", code: "JKL01 ...

The new experimental appDir feature in Next.js 13 is failing to display <meta> or <title> tags in the <head> section when rendering on the server

I'm currently experimenting with the new experimental appDir feature in Next.js 13, and I've encountered a small issue. This project is utilizing: Next.js 13 React 18 MUI 5 (styled components using @mui/system @emotion/react @emotion/styled) T ...

Using TypeScript, the Generator functions in Redux Saga do not execute nested effects in sequence when using yield put

I need to handle multiple asynchronous actions and ensure that a third action is only triggered after the first two have successfully completed. I have created three saga workers for this purpose: export function* emailUpdateRequestSaga(action: IEmailUpda ...