Меню

Ошибка parsing error unexpected token

With this code:

import React from 'react';
import { Link } from 'react-router';
import { View, NavBar } from 'amazeui-touch';

import * as Pages from '../components';

const {  Home, ...Components } = Pages;

I get this eslint error:

7:16  error  Parsing error: Unexpected token .. Why?

Here is my eslint config:

{
  "extends": "airbnb",
  "rules": {
    /* JSX */
    "react/prop-types": [1, {
      "ignore": ["className", "children", "location", "params", "location*"]
    }],
    "no-param-reassign": [0, {
      "props": false
    }],
    "prefer-rest-params": 1,
    "arrow-body-style": 0,
    "prefer-template": 0,
    "react/prefer-stateless-function": 1,
    "react/jsx-no-bind": [0, {
      "ignoreRefs": false,
      "allowArrowFunctions": false,
      "allowBind": true
    }],
  }
}

….
….
What’s the problem?

Brigand's user avatar

Brigand

83.1k19 gold badges163 silver badges170 bronze badges

asked Mar 15, 2016 at 2:19

DongYao's user avatar

2

Unexpected token errors in ESLint parsing occur due to incompatibility between your development environment and ESLint’s current parsing capabilities with the ongoing changes with JavaScripts ES6~7.

Adding the «parserOptions» property to your .eslintrc is no longer enough for particular situations, such as using

static contextTypes = { ... } /* react */

in ES6 classes as ESLint is currently unable to parse it on its own. This particular situation will throw an error of:

error Parsing error: Unexpected token =

The solution is to have ESLint parsed by a compatible parser, i.e @babel/eslint-parser or babel-eslint for babel version below v7.

just add:

"parser": "@babel/eslint-parser"

to your .eslintrc file and run npm install @babel/eslint-parser --save-dev or yarn add -D @babel/eslint-parser.

Please note that as the new Context API starting from React ^16.3 has some important changes, please refer to the official guide.

answered Apr 15, 2017 at 12:56

hanorine's user avatar

hanorinehanorine

6,8873 gold badges13 silver badges18 bronze badges

11

In my case (im using Firebase Cloud Functions) i opened .eslintrc.json and changed:

"parserOptions": {
  // Required for certain syntax usages
  "ecmaVersion": 2017
},

to:

"parserOptions": {
  // Required for certain syntax usages
  "ecmaVersion": 2020
},

Dmitry Grinko's user avatar

answered Sep 26, 2019 at 19:59

Alvin Konda's user avatar

Alvin KondaAlvin Konda

2,66821 silver badges22 bronze badges

3

ESLint 2.x experimentally supports ObjectRestSpread syntax, you can enable it by adding the following to your .eslintrc: docs

"parserOptions": {
  "ecmaVersion": 6,
  "ecmaFeatures": {
    "experimentalObjectRestSpread": true
  }
},

ESLint 1.x doesn’t natively support the spread operator, one way to get around this is using the babel-eslint parser. The latest installation and usage instructions are on the project readme.

answered Mar 15, 2016 at 6:19

Kevan Ahlquist's user avatar

Kevan AhlquistKevan Ahlquist

5,2151 gold badge17 silver badges23 bronze badges

6

"parser": "babel-eslint" helped me to fix the issue

{
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true,
            "modules": true,
            "experimentalObjectRestSpread": true
        }
    },
    "plugins": [
        "react"
    ],
    "extends": ["eslint:recommended", "plugin:react/recommended"],
    "rules": {
        "comma-dangle": 0,
        "react/jsx-uses-vars": 1,
        "react/display-name": 1,
        "no-unused-vars": "warn",
        "no-console": 1,
        "no-unexpected-multiline": "warn"
    },
    "settings": {
        "react": {
            "pragma": "React",
            "version": "15.6.1"
        }
    }
}

Reference

Rajendran Nadar's user avatar

answered Jul 25, 2017 at 9:56

7

I solved this issue by
First, installing babel-eslint using npm

npm install babel-eslint --save-dev

Secondly, add this configuration in .eslintrc file

{
   "parser":"babel-eslint"
}

answered Apr 4, 2019 at 4:04

Joee's user avatar

JoeeJoee

1,74416 silver badges18 bronze badges

1

Originally, the solution was to provide the following config as object destructuring used to be an experimental feature and not supported by default:

{
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true
    }
  }
}

Since version 5, this option has been deprecated.

Now it is enough just to declare a version of ES, which is new enough:

{
  "parserOptions": {
    "ecmaVersion": 2018
  }
}

answered Mar 16, 2020 at 16:12

Vojtech Ruzicka's user avatar

Vojtech RuzickaVojtech Ruzicka

15.9k15 gold badges63 silver badges64 bronze badges

I’m using eslint for cloud-functions (development env: flutter 2.2.3).

In my case .eslintrc.json does not exist so I had to update the .eslintrc.js file by including parserOptions: { "ecmaVersion": 2020, }, property at the end of file. My updated .eslintrc.js file looks like this:

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

answered Sep 23, 2021 at 6:49

sh_ark's user avatar

sh_arksh_ark

5375 silver badges14 bronze badges

1

Just for the record, if you are using eslint-plugin-vue, the correct place to add 'parser': 'babel-eslint' is inside parserOptions param.

  'parserOptions': {
    'parser': 'babel-eslint',
    'ecmaVersion': 2018,
    'sourceType': 'module'
  }

https://eslint.vuejs.org/user-guide/#faq

answered Feb 5, 2020 at 23:07

Cristiano's user avatar

CristianoCristiano

1342 silver badges4 bronze badges

I solved this problem by setting this in .eslintrc.json file:

"extends": [
    ...,
    "plugin:prettier/recommended"
]

Dharman's user avatar

Dharman

29.2k21 gold badges79 silver badges131 bronze badges

answered Sep 1, 2021 at 8:55

Pazu's user avatar

PazuPazu

1312 silver badges7 bronze badges

In febrary 2021 you can use theese values

ecmaVersion — set to 3, 5 (default), 6, 7, 8, 9, 10, 11, or 12 to specify the version of ECMAScript syntax you want to use. You can also set to 2015 (same as 6), 2016 (same as 7), 2017 (same as 8), 2018 (same as 9), 2019 (same as 10), 2020 (same as 11), or 2021 (same as 12) to use the year-based naming.

https://eslint.org/docs/user-guide/configuring/language-options#specifying-parser-options

answered Mar 3, 2021 at 17:18

Alexander Shestakov's user avatar

For React + Firebase Functions

Go to : functions -> .eslintrc.js

Add it —
parserOptions: {
ecmaVersion: 8,
},

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

answered May 14, 2022 at 6:37

Pankaj Kumar's user avatar

1

If you have got a pre-commit task with husky running eslint, please continue reading. I tried most of the answers about parserOptions and parser values where my actual issue was about the node version I was using.

My current node version was 12.0.0, but husky was using my nvm default version somehow (even though I didn’t have nvm in my system). This seems to be an issue with husky itself. So:

  1. I deleted $HOME/.nvm folder which was not deleted when I removed nvm earlier.
  2. Verified node is the latest and did proper parser options.
  3. It started working!

answered Oct 8, 2019 at 11:47

Asim K T's user avatar

Asim K TAsim K T

16.2k10 gold badges75 silver badges97 bronze badges

I was facing the issue despite implementing all the above solutions. When I downgraded the eslint version, it started working

answered May 5, 2021 at 18:46

Pravin Varma's user avatar

1

I’m using typescript and I solve this error change parser

....
"prettier/prettier": [
            "error",
            {
                .....
                "parser": "typescript",
                .....
            }
        ],
....

answered Apr 28, 2021 at 9:36

Dálcio Macuete Garcia's user avatar

2

.
.
{
    "parserOptions": {
    "ecmaVersion": 2020
},
.
.

Will do the trick.

answered Nov 14, 2022 at 7:09

Krishan Pal's user avatar

I had to update the ecmaVersion to "latest"

"parserOptions": {
    "parser": "@babel/eslint-parser",
    "sourceType": "module",
    "ecmaVersion": "latest",
    "ecmaFeatures": {
      "jsx": true,
      "experimentalObjectRestSpread": true
    },
    "requireConfigFile": false
  },

answered Nov 28, 2022 at 20:39

Philip Sopher's user avatar

Philip SopherPhilip Sopher

4872 gold badges5 silver badges18 bronze badges

Tell us about your environment

  • ESLint Version: 4.10.0
  • Node Version: 8.10.0
  • npm Version: 5.6.0

What parser (default, Babel-ESLint, etc.) are you using? babel-eslint

Please show your full configuration:

Configuration

{
  "extends": [
    "react-app",
    "plugin:flowtype/recommended",
    "plugin:jest/recommended",
    "prettier"
  ],
  "parser": "babel-eslint",
  "plugins": ["flowtype", "jest", "prettier"],
  "env": {
    "browser": true
  },
  "overrides": [
    {
      "files": ["src/**/*.spec.js"],
      "env": {
        "jest": true
      }
    }
  ],
  "rules": {
    "comma-dangle": ["error", "never"],
    "no-underscore-dangle": ["error", { "allowAfterThis": true }],
    "max-len": ["error", { "ignoreTrailingComments": true, "code": 100 }],
    "react/jsx-filename-extension": 0,
    "react/sort-comp": [
      "error",
      {
        "order": [
          "type-annotations",
          "state",
          "defaultProps",
          "static-methods",
          "lifecycle",
          "everything-else",
          "render"
        ]
      }
    ],
    "react/require-default-props": "off",
    "react/jsx-wrap-multilines": "off",
    "react/jsx-indent": "off",
    "react/jsx-indent-props": "off",
    "react/jsx-closing-bracket-location": "off",
    "class-methods-use-this": "off",
    "no-global-assign": 2,
    "no-param-reassign": "off",
    "no-plusplus": "off",
    "no-console": "error",
    "prettier/prettier": "error",
    "camelcase": [1, { "properties": "always" }],
    "no-unused-vars": [2, { "args": "after-used", "ignoreRestSiblings": true }]
  }
}

What did you do? Please include the actual source code causing the issue, as well as the command that you used to run ESLint.

import React from "react";

const ChatWidget = () => {
  return (
    <script>
      window.fcWidget.init({
        token: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
        host: "https://wchat.freshchat.com"
      });
    </script>
  );
};

export default ChatWidget;

which runs eslint src --max-warnings=0

What did you expect to happen?
I expected eslint to not flag anything.

What actually happened? Please include the actual, raw output from ESLint.

yarn run v1.7.0
$ eslint src --max-warnings=0

/Users/justinbrown/Sync/code/iu-react/src/components/ChatWidget/index.js
  7:14  error  Parsing error: Unexpected token, expected }

   5 |     <script>
   6 |       window.fcWidget.init({
>  7 |         token: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
     |              ^
   8 |         host: "https://wchat.freshchat.com"
   9 |       });
  10 |     </script>

✖ 1 problem (1 error, 0 warnings)

error Command failed with exit code 1.

Notes
I’ve looked through a number of Stack posts as well as issues posted on this repo. I’ve tried setting ecmaVersion explicitly as well as other suggestions as proposed in posts like: https://stackoverflow.com/questions/37918769/eslint-parsing-error-unexpected-token and #10369

Cover image for [ESLint] Parsing error: unexpected token =>

Arisa Fukuzaki

Hi there!

I’m Arisa, a freelance Full Stack Developer.

I’m developing Lilac, an online school with hands-on Frontend e-books and tutoring👩‍💻

What is this article about?

This is a solution when I saw these errors.

Parsing error: unexpected token =>

Enter fullscreen mode

Exit fullscreen mode

Warning: React version not specified in eslint-plugin-react settings. See https://github.com/yannickcr/eslint-plugin-react#configuration .

Enter fullscreen mode

Exit fullscreen mode

Project environment & full configuration

  • macOS: Catalina 10.15.7
  • VS Code

  • ESLint Version: ^7.15.0

  • Node Version: v12.18.2

  • npm Version: 6.14.5

"babel-eslint": "^10.1.0",
"babel-jest": "^22.4.1",
"babel-preset-env": "^1.6.1",
"concurrently": "^3.6.0",
"eslint": "^7.15.0",
"eslint-plugin-react": "^7.22.0",
"jest": "^22.4.2",
"webpack": "^3.10.0",
"webpack-dev-middleware": "^2.0.4",
"webpack-dev-server": "^2.11.1",
"webpack-hot-middleware": "^2.21.0"

Enter fullscreen mode

Exit fullscreen mode

A very simple project with JS(EcmaScript2016) with webpack, babel, jest and ESLint.

When did this error appear?

While I was running ESLint on my JS files.

How did it solve?

Reason

Lacking out of a package, babel-eslint to install.

Solution steps

  1. Install babel-eslint locally
$ yarn add --dev babel-eslint

Enter fullscreen mode

Exit fullscreen mode

Source: https://github.com/babel/babel-eslint

  1. Add "parser" config in .eslintrc.js
"parser": "babel-eslint"

Enter fullscreen mode

Exit fullscreen mode

Source: https://github.com/eslint/eslint/issues/10137

  1. Remove unnecessary config for non-React project
// "extends": [
//     "eslint:recommended",
//     "plugin:react/recommended"
// ],

Enter fullscreen mode

Exit fullscreen mode

Source: https://github.com/yannickcr/eslint-plugin-react#configuration

No errors✨

Summary

The biggest mistake I had was the React config in a JS project.

Normally, I use React and didn’t realize the wrong config for JS project🤦‍♀️

Hope this article was relevant for what you were looking for!

Happy new year & happy coding🎍

Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:

for var i = 1; i < 10; i++ {
<span style="font-weight: 400;">  // какой-то код</span>
<span style="font-weight: 400;">}</span>

После запуска в браузере цикл падает с ошибкой:

❌ Uncaught SyntaxError: Unexpected token ‘var’

Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.

Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.

Что делать с ошибкой Uncaught SyntaxError: Unexpected token

Когда интерпретатор не может обработать скрипт и выдаёт ошибку, он обязательно показывает номер строки, где эта ошибка произошла (в нашем случае — в первой же строке):

Интерпретатор обязательно показывает номер строки, где произошла ошибка Uncaught SyntaxError: Unexpected token

Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:

Строка с ошибкой Uncaught SyntaxError: Unexpected token

По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:

  • Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i<10; i++) {}
  • Посмотрите на предыдущие команды. Если там не закрыта скобка или кавычка, интерпретатор может ругаться на код немного позднее.

Попробуйте сами

Каждый из этих фрагментов кода даст ошибку Uncaught SyntaxError: Unexpected token. Попробуйте это исправить.

if (a==b) then  {}
function nearby(number, today, oneday, threeday) {
  if (user_today == today + 1 || user_today == today - 1)
    (user_oneday == oneday + 1 || user_oneday == oneday - 1)
      && (user_threeday == threeday + 1 || user_threeday == threeday - 1)
  return true
  
  else
     return false
}
var a = prompt('Зимой и летом одним цветом');
if (a == 'ель'); {
  alert("верно");
} else {
  alert("неверно");
}
alert(end);

Сообщение

SyntaxError: expected expression, got "x"
SyntaxError: expected property name, got "x"
SyntaxError: expected target, got "x"
SyntaxError: expected rest argument name, got "x"
SyntaxError: expected closing parenthesis, got "x"
SyntaxError: expected '=>' after argument list, got "x"

Тип ошибки

Что пошло не так?

Вместо определённой конструкции языка было использовано что-то другое. Возможно, просто опечатка.

Примеры

Ожидаемое выражение

Недопустимыми являются, к примеру, запятые после элементов цепочки выражений.

for (let i = 0; i < 5,; ++i) {
  console.log(i);
}
// SyntaxError: expected expression, got ';'

Правильным вариантом будет убрать запятую или добавить ещё одно выражение:

for (let i = 0; i < 5; ++i) {
  console.log(i);
}

Недостаточно скобок

Иногда можно потерять скобки при использовании if:

function round(n, upperBound, lowerBound){
  if(n > upperBound) || (n < lowerBound){
    throw 'Число ' + String(n) + ' больше, чем ' + String(upperBound) + ', или меньше, чем ' + String(lowerBound);
  }else if(n < ((upperBound + lowerBound)/2)){
    return lowerBound;
  }else{
    return upperBound;
  }
} // SyntaxError: expected expression, got '||'

На первый взгляд кажется, что скобки расставлены правильно, но обратите внимание, что || находится не в скобках. Необходимо заключить || в скобки:

function round(n, upperBound, lowerBound){
  if((n > upperBound) || (n < lowerBound)){
    throw 'Число ' + String(n) + ' больше, чем ' + String(upperBound) + ', или меньше, чем ' + String(lowerBound);
  }else if(n < ((upperBound + lowerBound)/2)){
    return lowerBound;
  }else{
    return upperBound;
  }
}

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка pr2 на рефрижераторе
  • Ошибка pnp detected fatal error