Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ES6(esm) imports/exports in cloud functions

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

like image 825
Igor Kokotko Avatar asked Jan 24 '20 22:01

Igor Kokotko


People also ask

How do ES6 modules work?

A module is nothing more than a chunk of JavaScript code written in a file. By default, variables and functions of a module are not available for use. Variables and functions within a module should be exported so that they can be accessed from within other files. Modules in ES6 work only in strict mode.

How many parts are there in ES6 module?

The ES6 module standard has two parts: Declarative syntax (for importing and exporting) Programmatic loader API: to configure how modules are loaded and to conditionally load modules.


2 Answers

"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')
like image 67
Muhammad Usman Avatar answered Sep 28 '22 08:09

Muhammad Usman


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!");
});
like image 30
wiesson Avatar answered Sep 28 '22 08:09

wiesson