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

Confirm that the dependency has been invoked using Sinon

I am currently working on testing whether a dependency has been called or not. Here is an example of my code: export default class vehicle { private builder: CarBuilder; constructor() { this.builder = CreateCar(); <- factory return fake data } crea ...

Troubles with input handling in Angular

I've been diving into Traversy Media's Angular crash course recently. However, I've hit a roadblock that I just can't seem to get past. The problem arises when trying to style the button using a specific method. Every time I save and pa ...

Receiving an error stating "module not found" when attempting to retrieve the NextAuth session using EmailProvider in getServerSideProps

Trying to access the NextAuth session from a server-side call within getServerSideProps, using an EmailProvider with NextAuth. Referring to an example in NextAuth's documentation, I'm attempting to retrieve the session from getServerSideProps. T ...

No invocation of 'invokeMiddleware' was suggested

Encountered this specific issue when setting up loopback4 authentication. constructor ( // ---- INSERT THIS LINE ------ @inject(AuthenticationBindings.AUTH_ACTION) protected authenticateRequest: AuthenticateFn, ) { super(authen ...

The element in the iterator in next.js typescript is lacking a necessary "key" prop

Welcome to my portfolio web application! I have created various components, but I am facing an issue when running 'npm run build'. The error message indicates that a "key" prop is missing for an element in the iterator. I tried adding it, but the ...

What is the best way to pass a conditional true or false value to React boolean props using TypeScript?

I am currently utilizing the Material UI library in combination with React and Typescript. Whenever I attempt to pass a conditional boolean as the "button" prop of the component, I encounter a typescript error stating: Type 'boolean' is not assi ...

New to React and struggling with updating the DOM

Upon receiving a React project, I am faced with the task of performing a complex state update on my DOM. Here is how my component looks: /** @jsx jsx */ import { jsx } from '@emotion/core'; import { Typography } from '@material-ui/core&ap ...

Cheerio fails to retrieve items from the specified directory

My main goal with cheerio is to scrape the titles from this IMDb ranking: Despite following the documentation and specifying the exact HTML path for the titles, I am getting back random and confusing objects like: 'x-attribsNamespace': [Object ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

Implementing Firebase-triggered Push Notifications

Right now, I am working on an app that is built using IONIC 2 and Firebase. In my app, there is a main collection and I am curious to know if it’s doable to send push notifications to all users whenever a new item is added to the Firebase collection. I ...

Types are not appearing in @types/node

I have added @types/node to my project. In the index.ts file, the default node modules are being treated as type any. const fs = require('fs'); The type of fs is currently set to any. { "ts-node": { "cwd": "/User ...

How to determine the frequency of a specific word in a sentence using Angular 5

I need help finding a solution to count how many times a word appears in sentences. Input: k = 2 keywords = ["anacell", "cetracular", "betacellular"] reviews = [ "Anacell provides the best services in the city", "betacellular has awesome services", ...

Error message saying "Firebase not defined after Ember CLI installation using npm"

After completing the necessary steps in the command line to set up Ember CLI, Firebase, and EmberFire using node, I encountered an issue where Firebase is not defined in app/adapter/application.js npm install -g ember-cli npm install -g bower npm instal ...

Tips for maintaining the selection when switching pages with smart-table?

I have implemented smart-table in my project to allow users to select records from different pages and view them in a preview section. However, I am facing an issue where the selection made on the first page does not persist when navigating back to it aft ...

The second guard in Angular 5 (also known as Angular 2+) does not pause to allow the first guard to complete an HTTP request

In my application, I have implemented two guards - AuthGuard for logged in users and AdminGuard for admins. The issue arises when trying to access a route that requires both guards. The problem is that the AdminGuard does not wait for the AuthGuard to fini ...

Warning: Potential spacing issues when dynamically adjusting Material UI Grid using Typescript

When working with Typescript, I encountered an error related to spacing values: TS2322: Type 'number' is not assignable to type 'boolean | 7 | 2 | 10 | 1 | 3 | 4 | 5 | 6 | 8 | "auto" | 9 | 11 | 12'. No lint errors found Version: typesc ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Error: Unexpected token < occurs when using SVG require in Jest

I'm struggling to locate the source of this error. Currently, I am working with Typescript in React and using Jest and Enzyme for unit testing. Below is a snippet from my Package.json file: "scripts": { "start": "node server.js", "bundle": ...

What is the best way to utilize a union of interfaces in TypeScript when working with instances?

Review this TypeScript snippet: class A {public name: string = 'A';} interface B {num: number;} class Foo { get mixed(): Array<A | B> { const result = []; for (var i = 0; i < 100; i ++) { result.push(Mat ...

React: Avoid unnecessary re-rendering of child components caused by a bloated tree structure

I am dealing with a tree/directory structured data containing approximately 14k nodes. The issue I am facing is that every time a node is expanded or minimized by clicking a button, causing it to be added to an 'expanded' Set in the Redux state, ...