Search code examples
firebasegoogle-cloud-functionsfirebase-tools

firebase emulator cannot refresh dynamic import Functions


Background I use dynamic import for Firebase Functions to reduce cold start time based on this post: https://medium.com/firebase-developers/organize-cloud-functions-for-max-cold-start-performance-and-readability-with-typescript-and-9261ee8450f0

index.ts under functions folder has only one line

exports.consent = require("./myFunctionGroup");

index.ts under functions/myFunctionGroup

import * as functions from "firebase-functions";

export const helloWorld = functions.https.onCall(async (data, context) => {
  return await (await import("./helloWorld")).default(data, context);
});

Content of helloWorld.ts under functions/myFunctionGroup

import * as functions from "firebase-functions";

export default async (
  data: {},
  context: functions.https.CallableContext
) => {
    return "hello";
}

There is no problem when the emulator first launched as it return "hello" correctly. However, when I change to return to 'return "world";', even though the emulator seems to be aware of the change and prints ✔ functions: Loaded functions definitions from source:..., it still return the old value of hello. Maybe it has some kind of cache for the original imported module. When I restart process again, then it will then print "world".

Question: Is there any setting to make the emulator aware my change and force to clear the Functions cache? I tried to use debugger and it realized my code has changed so that I can step through the new code. It's just not working for the Firebase emulator.


Solution

  • It was expected behavior,any changes/modification in the code after running the emulator will not be reflected. You can also refer to this documentation:

    Note:Code changes you make during an active session are automatically reloaded by the emulator. If your code needs to be transpiled (TypeScript, React) make sure to do so before running the emulator. You can run your transpiler in watch mode with commands like tsc -w to transpile and reload code automatically as you save.

    You can follow the below steps,As mentioned in this stackoverflow thread

    • After every change to the ts files, run "npm run build" to compile the code again.
    • Change "build": "tsc" to "build": "tsc -w" in package.json if you want to auto-compile after every change.

    There is a bug raised for this at github which is still open you can track the updates there.