8
import functions from 'firebase-functions';
import UtilModuler from '@utilModuler'

exports.helloWorld = functions.https.onRequest((request, response) => {
 response.send("Hello from Firebase!");
});

import UtilModuler from '@utilModuler'; ^^^^^^^^^

SyntaxError: Unexpected identifier at Module._compile (internal/modules/cjs/loader.js:721:23)

Caveats

I'm using third party libraries(@utilModuler) which were written via import/exports. Possible workarounds:

  1. Fork library and generate cjs file with rollup.
  2. esm works like a charm but it cause unnesecary memory consumptions

Question: is there are a way how to use hybrid import cjs and esm in google cloud function?(except options which I described above)

Would be nice to use in deploy function something like --experimental-modules

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Igor Kokotko
  • 488
  • 1
  • 5
  • 13

2 Answers2

5

It looks like, ESM support has been added by the latest version of the firebase CLI (https://github.com/firebase/firebase-tools/releases/tag/v9.15.0):

$ npm install -g firebase-tools # Get the latest firebase-cli
$ firebase deploy --only functions # Deploy as usual

and

  1. You must select nodejs14 runtime.
  2. You must manually include latest version of @google-cloud/functions-framework dependency. e.g.
// package.json
...
  "engines": {
    "node": "14"
  },
  "type": "module",
  "dependencies": {
    "@google-cloud/functions-framework": "^1.9.0",
    ...
  },

and an example function:

// index.js
import functions from "firebase-functions";

export const helloWorld = functions.https.onRequest((request, response) => {
  response.send("Hello from Firebase!");
});
wiesson
  • 6,544
  • 5
  • 40
  • 68
  • 1
    Note: If using GCP Cloud Functions (not through Firebase) they automatically include the latest `@google-cloud/functions-framework` as noted by one of the authors in https://medium.com/google-cloud/es-modules-in-cloud-functions-f5be1676c8b5 – jthegedus Aug 15 '21 at 02:30
  • Can someone please help? The answer works fine, but when I use this, it says "Must use import to load ES Module: .eslintrc.js" – Andrew Dec 26 '21 at 16:14
  • 1
    you don't need `"@google-cloud/functions-framework": "^1.9.0",` anymore as of 2023 – Antoine Weber Feb 13 '23 at 22:57
1
"devDependencies": {
  "@babel/core": "^7.2.0",
  "@babel/preset-env": "^7.2.0",
  "@babel/register": "^7.0.0"
}

.babelrc

{
  "presets": ["@babel/preset-env"]
}

entry point node.js app

require("@babel/register")({})

// Import the rest of our application.
module.exports = require('./index.js')
Muhammad Usman
  • 1,220
  • 13
  • 22