"Unexpected token" 为 firebase 函数使用箭头函数时

"Unexpected token" when using arrow function for firebase functions

我在尝试将我的函数部署到 firebase 时遇到 ESLint 错误。具体来说,当我认为 firebase 支持箭头函数时,它似乎不喜欢箭头函数。我正在使用默认提供的 ESLint 使用 firebase init functions.

初始化函数文件
/root/functions/helpertools.js
  62:84  error  Parsing error: Unexpected token =>

第 62 行是以下代码块中的第一个:

const getCostEstimateBetweenPlaceIDs = async (placeIdOrigin,placeIDdestination)=> {
    let routeInfo = await calculateRoute(placeIdOrigin,placeIDdestination,true)
    let minutes = convertHourMinTextToMinutes(routeInfo.duration)
    let miles = convertKMTextToMiles(routeInfo.distance)

    return {cost:uberCostEstimate(minutes,miles),minutes:minutes,miles:miles}
}

我的.eslintrc.js如下:

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

来自我的package.json:

    "@eslint/eslintrc": {
      "version": "0.4.3",
      "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-0.4.3.tgz",
      "integrity": "sha512-J6KFFz5QCYUJq3pf0mjEcCJVERbzv71PUIDczuh9JkwGEzced6CO5ADLHB1rbf/+oPBtoPfMYNOpGDzCANlbXw==",
      "dev": true,
      "requires": {
        "ajv": "^6.12.4",
        "debug": "^4.1.1",
        "espree": "^7.3.0",
        "globals": "^13.9.0",
        "ignore": "^4.0.6",
        "import-fresh": "^3.2.1",
        "js-yaml": "^3.13.1",
        "minimatch": "^3.0.4",
        "strip-json-comments": "^3.1.1"
      }
    },

来自我的包裹-lock.json:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "14"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^9.8.0",
    "firebase-functions": "^3.14.1"
  },
  "devDependencies": {
    "eslint": "^7.6.0",
    "eslint-config-google": "^0.14.0",
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}

我已经对此进行了测试,我确认您确实需要做两件事,以解决您面临的问题,将您的 package.json 脚本部分更改为以下内容:

"scripts": { "lint": "eslint", ... } 而不是默认的 “scripts”: {“lint”:”eslint .”, …}。 因此,从那里删除 .,即 auto-generated,但可能会导致此类问题。

箭头函数是 ES6 的一个特性,但这里有一个异步箭头函数。 异步函数通常是 ES8(或 2017)的特性。因此,您需要指定将解析器的 ecmaVersion 更改为版本 8,因此将 .eslintrc.js 文件更改为:

parserOptions: { parser: 'babel-eslint', ecmaVersion: 8, },

这将使解析器知道在使用异步后需要 => 标记。