Using ES6+ in Firebase Functions with Babel

Blessing Pariola
2 min readJan 28, 2018

--

ES6 in Cloud Functions for Firebase

In this post I explain how to use ES6+code in your Cloud Functions. Since ES6+ features are not all supported we would be using babel for transpiling.

If you don’t know how to setup a Cloud Function, please refer to this post 💯.

Now that we have a basic function, lets write some ES6+ code

Restructuring

Rename functions to anything else, I suggest using app .

Now setup a package.json in the root folder to automate scripts. Run npm init -y in the root folder which accepts all options.

Install babel & rimraf with npm i rimraf babel-cli babel-preset-env --save-dev .

NPM scripts (automating the boring stuff!!) 😎

Now we have the packages and folder structure we need, let’s add our scripts.

Putting this down, we want babel to transpile all JavaScript files in the ./app directory and output the Node compatible results to the ./functions directory. After transpiling, using the specified babel preset, a copy of all files Babel didn’t touch are moved to the destination. It should ignore the node_modules directory because they are all ES5 compatible.

Add a scripts node to your package.json.

Name your scripts however you like. I’m using build.

"build": "babel app --out-dir functions --copy-files --ignore app/node_modules"

Create .babelrc configuration file

Paste this into .babelrc which tells babel to convert to firebase’s version compatible:

{
"presets": [
["env", {
"targets": {
"node": "6.11.5"
}
}]
]
}

Note: If you try to deploy to firebase now you’ll come across an error . This is because the new functions directory doesn’t have any node_modules.

Now, we have to install the packages after babel transpiles. Ever heard of pre & post hooks in npm, read more here.

Add this script "postbuild": "cd functions && npm i -s" to your ./package.json. So after transpiling packages are installed in the functions directory.

Also since we would like to clean the functions directory on every build. Let’s hook it up "prebuild": "node node_modules/rimraf/bin functions" .

To deploy add "deploy": "npm run build && firebase deploy" .

Your ./package.json should look

And ./app/package.json like this:

Deploy 🚀

Go ahead and deploy by running npm run deploy in the root directory.

Done 💯

If you found this useful, please recommend and share with your friends & colleagues. ❤️

--

--