Looks like Cloud Functions does not support Async-Await notation. Is there a way I could use Babel until they do or is it recommended to use promises?
My current function that sits on Node is like so:
exports.getToken = async (req, res) => {
//1. Generate token from Braintree
const result = await gateway.clientToken.generate();
//2. Return the client token
res.json(result.clientToken);
};
Cloud Functions runs the LTS version of node.js, which according to the documentation is 6.14.0 at this moment in time. node 6.x supports EcmaScript 6, which does not include async/await.
However, you can write your code in TypeScript and have that transpiled down to ES5/ES6, which will effectively convert the use of async/await into promises. A web search suggests that perhaps this plugin can be used to help Babel with similar transpiling.
It's worth noting that the Firebase CLI now allow you to initialize a new Cloud Functions project with native TypeScript support, which is what the Firebase team is currently recommending to developers.
If you don't want to use TypeScript, you can now also choose node 8 (which is currently in beta, and does support async/await for plain JavaScript) as a deployment target. You can follow the documentation to edit your package.json to indicates that your functions should be deployed to node 8.
Now you can use Node.js version 8 by adding this in your functions/package.json
:
"engines": {
"node": "8"
}
Example: https://github.com/firebase/functions-samples/blob/Node-8/authenticated-json-api/functions/package.json
Instead of transpile TypeScript, I have transpiled my javascript after follow this very nice post and take a look at this repository
Basically you can do:
npm install -g @babel/cli @babel/core @babel/preset-env
UPDATE:
I'm having troubles with version "7.0.0-beta.51" of babel. "7.0.0-beta.44" still ok.
Switch to stable version 6
npm install --save-dev babel-cli babel-preset-env
Create the file .babelrc inside your project folder
{
"presets": [
["@babel/env", {
"targets": {
"node": "6.11.5"
}
}]
]
}
Move your "functions" folder to "firebaseFunctions" folder and then run
babel firebaseFunctions --out-dir functions --copy-files --ignore firebaseFunctions/node_modules
Or run this command for each files you want to transpile
babel originalfile.js --out-file transpiledfile.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With