Firebase functions cannot deploy : SyntaxError: Unexpected token function

13,880

Solution 1

As of September 2019:

  1. Update firebase-admin : npm install --save firebase-admin
  2. Update firebase-functions : npm install --save firebase-functions
  3. Add "engines": { "node": "10" } to your /functions/package.json
...
"dependencies": {
    "firebase-admin": "^8.5.0",
    "firebase-functions": "^3.2.0"
  },
  "devDependencies": {
    "tslint": "~5.19.0",
    "typescript": "~3.6.2"
  },
  "engines": {
    "node": "10"
  }
...

As of August 2018:

Cloud Functions now support Node 8 (8.11.1). Check out this blog post.

Upgrade to Node 8

As suggested in this blog post, follow these steps to upgrade to Node 8:

  1. Upgrade your firebase-functions version via npm install --save firebase-functions@latest
  2. Upgrade firebase-tools via npm update -g firebase-tools
  3. Add "engines": { "node": "8" } to your /functions/package.json

Solution 2

If you are still having the issue on a recent version (such as node 12), use the ecmaVersion parser option in your .eslintrc.js file.

Here's a sample:

module.exports = {
  root: true,
  env: {
    es6: true,
    node: true,
  },
  parserOptions: {
    ecmaVersion: 8,
  },
  extends: [
    "eslint:recommended",
    "google",
  ],
  rules: {
    quotes: ["error", "double"],
  },
};

h/t to Dean for the original suggestion.

Share:
13,880

Related videos on Youtube

Gerardo BLANCO
Author by

Gerardo BLANCO

In addition to trying to conquer the world, I am a Full Stack developer focused on developing products with excellent quality, fast, intuitive, functional and with excellent UX / UI. I have 4 years of experience. The first 2 years were in FreeLancer format, selling and developing informational pages for all types of companies. The last 2 years working in a diverse and dynamic environment that uses different tools and programming languages, to implement systems within a financial company. I love a job or project when I can: Learn new languages and frameworks. Lead the projects and make things happen. Deploy and improve life of others. I count on: Deep knowledge in programming languages, such as Java, Python, PHP, JS, SQL, HTML, CSS, etc .; Database designer and architect; Debbuger natural; Agile in the veins; Git guruness; Good negotiation treatment; Experience with TDD; A true Clean Coder; Advanced English; Among other things; I'm happy if I have a problem to solve and something new to learn. SPANISH: Además de intentar conquistar el mundo, soy un desarrollador Full Stack enfocado en desarrollar productos con gran calidad, rápidos, intuitivos, funcionales y con excelente UX / UI. Cuento con 4 años de experiencia. Los primeros 2 años fueron en formato de FreeLancer, vendiendo y desarrollando paginas informativas para todo tipo de empresas. Los últimos 2 años trabajando en un entorno diverso y dinámico que utiliza diferentes herramientas y lenguajes de programación, para implementar sistemas dentro de una empresa financiera. Amo mi trabajo o el proyecto cuando puedo ... Aprender nuevos lenguajes y frameworks. Adueñarse de los proyectos y hacer que las cosas sucedan. Implementar un sistema y mejora la vida de los demás. Cuento con: Profundo conocimiento en lenguajes de programación, tales como Java, Python, PHP, JS, SQL, HTML, CSS, etc.; Diseñador y arquitecto de bases de datos; Debbuger natural; Agile en las venas; Git guruness; Buen trato de negociación; Experiencia con TDD; Un verdadero Clean Coder; Inglés avanzado. Entre otras cosas. I'm happy if I have a problem to solve and something new to learn.

Updated on July 24, 2022

Comments

  • Gerardo BLANCO
    Gerardo BLANCO almost 2 years

    I am trying to deploy a function to firebase and I get an error during deployment

    Error: Functions did not deploy properly.

    Could it be linked with the async function ?

    Actual behavior Functions get deployed with errors, the cli shows me the following message:

    ================ console log ================

    > eslint .
    ✔  functions: Finished running predeploy script.
    i  functions: ensuring necessary APIs are enabled...
    ✔  functions: all necessary APIs are enabled
    i  functions: preparing functions directory for uploading...
    i  functions: packaged functions (56.39 KB) for uploading
    ✔  functions: functions folder uploaded successfully
    i  functions: updating function sendContactEmailOAuth...
    ⚠  functions[sendContactEmailOAuth]: Deployment error.
    Function load error: Code in file index.js can't be loaded.
    Is there a syntax error in your code?
    Detailed stack trace: /user_code/index.js:13
     async function getJwt() {
           ^^^^^^^^
    

    ================ functions index.js file ================

    const functions = require('firebase-functions');
    
    
    const admin = require('firebase-admin');
       admin.initializeApp();
    
       const { JWT } = require('google-auth-library/build/src/index');
    
       exports.sendContactEmailOAuth = functions.https.onRequest((req, res) => {
     const sender_msg = 'just a test'
     const email = '[email protected]'
    
     async function getJwt() {
       const client = new JWT(
         functions.config().service_key.client_email,
         null,
         functions.config().service_key.private_key,
         ['https://www.googleapis.com/auth/cloud-platform', 'https://mail.google.com'],
       );
         await client.authorize();
          const url = `https://www.googleapis.com/dns/v1/projects/${functions.config().service_key.project_id}`;
       const res = await client.request({ url });
       console.log(res.data);
     }
    
    getJwt();
    
      /*  send email with nodemailer to be inserted here */
     });
    

    ================ package.json file ================

    {
     "name": "functions",
     "description": "Cloud Functions for Firebase",
     "scripts": {
       "lint": "eslint .",
       "serve": "firebase serve --only functions",
       "shell": "firebase functions:shell",
       "start": "npm run shell",
       "deploy": "firebase deploy --only functions",
       "logs": "firebase functions:log"
     },
     "dependencies": {
       "firebase-admin": "~5.12.0",
       "firebase-functions": "^1.0.2",
       "firebase-tools": "^3.18.4",
       "google-auth-library": "^1.4.0",
       "nodemailer": "^4.6.4"
     },
     "devDependencies": {
       "eslint": "^4.12.0",
       "eslint-plugin-promise": "^3.6.0"
     },
     "private": true
     }
    
    • Yulian
      Yulian over 5 years
      could you please have a look at my answer and consider marking it as the accepted one?
  • gugateider
    gugateider over 5 years
    This should be the accepted answer. Have helped me a ton!! Thanks Yulian!
  • Eureka
    Eureka over 5 years
    @erwin it would be good if you mark this as the accepted answer, since the situation has changed from the time you accepted the original answer. Most users will want this answer.
  • Dean Stamler
    Dean Stamler over 5 years
    If anybody is getting linting errors after doing the updates, make sure that "ecmaVersion": 8 is set in your .eslintrc.json as well.
  • Leo
    Leo almost 5 years
    @DeanStamler Thanks for the hint. I have tried to add this to packages.json, but I can't get it to work. github.com/eslint/eslint/issues/11976
  • Michał Kaczanowicz
    Michał Kaczanowicz over 4 years
    Unfortunately at this moment (January 2020) it's not working for me, anyone has a clue?