Ошибка 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...

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.2k19 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,9263 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,75416 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

16k15 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

5475 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.3k21 gold badges80 silver badges131 bronze badges

answered Sep 1, 2021 at 8:55

Pazu's user avatar

PazuPazu

1412 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 badges76 silver badges98 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

In this post, we will explore – How To Fix – “Parsing Error: Unexpected Token” in React.

error Parsing error: Unexpected token
ESLint Parsing Error: Unexpected token {
Parsing error: Unexpected token =>
SyntaxError: Unexpected token (

Such “Unexpected token” signify a common behavioural problem  – somewhere in your code a specific construct was supplied, but the system expected something completely different (based on defined rulescustoms). This could be due to a typo mistake, missing something in the code etc. Also could be dev environment and ESLint parsing styles are not compatible owing to the changes for various or upgraded versions.


if( aicp_can_see_ads() ) {

}

Before we try to fix, Let’s do some primitive checks to pinpoint some of the symptoms.

Primitive Check:

  • What version of React are you using ?
  • Have you considered and cross-checked that you have correctly “imported” everything ?
  • Are you able to compile your code using Babel ?
  • Have you tried babel-eslint parser – the newer name is @babel/eslint-parser
  • Does it work in the Browser ?

Once you have been through all the above pointers, try the below options.

Try the latest babel eslint and make sure you follow the compatibility matrix.


if( aicp_can_see_ads() ) {

}

ESLint babel-eslint
4.x >= 6.x
3.x >= 6.x
2.x >= 6.x
1.x >= 5.x

Node version preferably should be 8+.

  • Do the install. The “x.x” & “y” below has to be substituted appropriately as per the above table.
npm install [email protected]x.x [email protected]y --save-dev

OR

yarn add [email protected]x.x [email protected]y -D


if( aicp_can_see_ads() ) {

}

  • Go to the .eslintrc (or .eslintrc.json) config file and make the below changes.

Also check what value you have in “.babelrc”.

{
  "parser": "babel-eslint",
}

If above doesn’t work, you could also try,

{
 "parser: "@babel/eslint-parser"
}
  • If applicable, go to your package.json file and check the below.
"scripts": {
    "lint": "eslint"
},
  • You might have two files in your system. There are different versions of ecmaScript with the same name,
    • .eslintrc.js -> es6: true – which was released on June 2015
    • .eslintrc.json -> “ecmaVersion”: 2017 – which is equivalent to es8

If the wrong ecmaScript is being picked up in your case, you can try removing the “.eslintrc.js” file (so as to avoid the conflict) and see if that helps to solve the error.


if( aicp_can_see_ads() ) {

}

  • You can also try changing the ecmaVersion in the .eslintrc.json file.
"parserOptions": {
      // Required for certain syntax usages
      "ecmaVersion": 2020
},

You could also try other values like 2017, 2018 instead of 2020

You can use one of the below ecmaVersion value to specify what version of ECMAScript syntax to use-


if( aicp_can_see_ads() ) {

}

    • 3
    • 5 (default)
    • 6 (also used as 2015)
    • 7 (also used as 2016)
    • 8 (also used as 2017)
    • 9 (also used as 2018)
    • 10 (also used as 2019)
    • 11 (also used as 2020)
    • 12 (also used as 2021)

Hope this helps to solve the error.

Other Interesting Reads –

  • How to Send Large Messages in Kafka ?

  • Fix Spark Error – “org.apache.spark.SparkException: Failed to get broadcast_0_piece0 of broadcast_0”

  • How to Handle Bad or Corrupt records in Apache Spark ?

  • How to use Broadcast Variable in Spark ?

  • How to log an error in Python ?

  • How to Code Custom Exception Handling in Python ?

  • How to Handle Errors and Exceptions in Python ?

  • How To Fix – “Ssl: Certificate_Verify_Failed” Error in Python ?

  • How to Send Large Messages in Kafka ?

  • Fix Spark Error – “org.apache.spark.SparkException: Failed to get broadcast_0_piece0 of broadcast_0”

  • How to Handle Bad or Corrupt records in Apache Spark ?

  • How to use Broadcast Variable in Spark ?

  • Best Practices for Dependency Problem in Spark

  • Sample Code – Spark Structured Streaming vs Spark Streaming

  • Sample Code for PySpark Cassandra Application

  • How to Enable UTF-8 in Python ?

  • How to log an error in Python ?

  • Sample Python Code To Read & Write Various File Formats (JSON, XML, CSV, Text)

  • How to Handle Errors and Exceptions in Python ?

  • How to Handle Bad or Corrupt records in Apache Spark ?

  • How To Fix – Partitions Being Revoked and Reassigned issue in Kafka ?

  • What Are The Most Important Metrics to Monitor in Kafka ?

  • How To Connect Local Python to Kafka on AWS EC2 ?

  • How to Send Large Messages in Kafka ?

  • Fix Spark Error – “org.apache.spark.SparkException: Failed to get broadcast_0_piece0 of broadcast_0”


if( aicp_can_see_ads() ) {

}

parsing error: unexpected token javascript ,parsing error : unexpected token servicenow ,parsing error: unexpected token typescript ,parsing error: unexpected token vue ,parsing error: unexpected token node js ,parsing error: unexpected token salesforce ,parsing error: unexpected token import ,parsing error: unexpected token eslint typescript , , ,error parsing error: unexpected token eslint ,error parsing error: unexpected token => ,error parsing error: unexpected token javascript ,error parsing error: unexpected token => firebase ,parsing error: unexpected token node js ,how do i fix unexpected token parsing error ,parsing error: unexpected token import ,parsing error unexpected token in servicenow , , ,parsing error: invalid ecmaversion 2021 ,parsing error: invalid ecmaversion 13 ,eslint ecmaversion ,parsing error: ecmaversion must be a number. ,ecmaversion 2022 ,ecmaversion 12 ,ecmaversion'': latest ,eslint ecmaversion latest ,parsing error: unexpected token ,parsing error unexpected token ,parsing error unexpected token expected ,parsing error unexpected token javascript ,parsing error unexpected token function ,parsing error unexpected token node js ,parsing error unexpected token import ,parsing error unexpected token in servicenow ,parsing error unexpected token expected typescript ,parsing error unexpected token axios ,parsing error unexpected token await ,parsing error unexpected token assert eslint ,parsing error unexpected token aws lambda ,parsing error unexpected token angular ,parsing error unexpected token as.eslint-plugin-vue ,parsing error unexpected token axios eslint ,parsing error unexpected token async eslint ,parsing error unexpected token brackets ,error parsing json unexpected token bracket. (15360) ,error parsing json unexpected token bracket ,json parse error unexpected identifier bad ,babel parse error unexpected token ,what is parsing error unexpected token ,what causes parsing error ,what does parsing error mean ,parsing error unexpected token const ,parsing error unexpected token constructor ,parsing error unexpected token colon ,parsing error unexpected token css ,parsing error unexpected token catch servicenow ,parsing error unexpected token. a constructor method accessor or property was expected ,parsing error unexpected token . optional chaining ,parsing error unexpected token try catch ,parsing error unexpected token declare global ,parsing error unexpected token doctype html ,parsing error unexpected token db ,parsing error unexpected token dreamweaver ,parsing error unexpected token. did you mean ' ' or &rbrace ,parsing error unexpected token doctype ,parsing error unexpected token dynamodb ,parsing error unexpected token data ,parsing error unexpected token eslint ,parsing error unexpected token expected vue ,parsing error unexpected token else ,parsing error unexpected token expected map ,parsing error unexpected token expected in react js ,parsing error unexpected token eslint vue ,parsing error unexpected token fetch ,parsing error unexpected token = firebase ,parsing error unexpected token (fatal) ,parsing error unexpected token expected from ,parsing error unexpected token = arrow function ,parsing error unexpected token react function ,parsing error unexpected token = eslint arrow function ,parsing error unexpected token glitch ,parsing error unexpected token global ,parse error syntax error unexpected token global ,parsing error unexpected token . did you mean or ,godot parser error unexpected token ,error in parse unexpected symbol ,parsing error unexpected token html ,parsing error unexpected token head ,json parse error unexpected identifier https ,json parse error unexpected token pizza hut ,parse error syntax error unexpected identifier header ,json parse error unexpected token pizza hut app ,parse errors in imported module unexpected token head ,parsing error unexpected token in react js ,parsing error unexpected token in javascript ,parsing error unexpected token if ,parsing error unexpected token in eslint ,parsing error unexpected token import react lazy ,parsing error unexpected token jsx ,parsing error unexpected token json ,parsing error unexpected token javascript servicenow ,parsing error unexpected token vue js ,parsing error unexpected token expected javascript ,eslint parsing error unexpected token json ,parsing error unexpected token expected keyof ,parser error unexpected token expected identifier keyword or string ,js_parse_error syntaxerror unexpected token keyword «const» ,parsing error unexpected token lambda ,parsing error unexpected token lint ,parsing error unexpected token let ,parsing error unexpected token lwc ,parsing error unexpected token expected lwc ,parser error unexpected token lexer error ,parser error unexpected token lexer error unterminated quote ,parsing error unexpected token module ,parse error syntax error unexpected token match ,parse error syntax error unexpected token match expecting ,parse error syntax error unexpected token match expecting variable ,parse error syntax error unexpected identifier mysqli_query ,parsing error unexpected token namespace ,parsing error unexpected token name ,parsing error unexpected token node ,parsing error unexpected token new ,parsing error unexpected token npm ,parser error unexpected token '=' ngmodel ,parsing error unexpected token react native ,parsing error unexpected token optional chaining ,parsing error unexpected token of ,parsing error unexpected token spread operator ,eslint parsing error unexpected token in typescript cast operator as ,json parse error unexpected token o ,json parse error unexpected identifier object ,parser error unexpected token expected identifier or keyword ,json parse error unexpected identifier ok ,parsing error unexpected token prettier/prettier ,parsing error unexpected token promise ,parsing error unexpected token private ,parsing error unexpected token promise eslint ,parsing error unexpected token python ,parsing error unexpected token .eslint-plugin-vue ,parsing error unexpected token expected package.json ,eslint parsing error unexpected token expected ,parsing error unexpected token question mark ,parsing error unexpected token react ,parsing error unexpected token return eslint ,parsing error unexpected token request ,parsing error unexpected token expected react ,parsing error unexpected token expected react js ,parsing error unexpected token servicenow ,parsing error unexpected token salesforce ,parsing error unexpected token source ,parsing error unexpected token s3 ,parsing error unexpected token standard ,parsing error unexpected token scss ,parsing error unexpected token switch ,parsing error unexpected token typescript ,parsing error unexpected token type ,parsing error unexpected token throw ,parsing error unexpected token tampermonkey ,parsing error unexpected token ts ,parsing error unexpected token template ,vue parsing error unexpected token template ,parsing error unexpected token useeffect ,parsing error unexpected token user ,parsing error unexpected token ui5 ,json parse error unexpected token u ,json.parse error unexpected token u in json at position 0 ,parsing error unexpected token in sap ui5 ,json parse error unexpected identifier undefined ,parse error syntax error unexpected token use ,parsing error unexpected token vue ,parsing error unexpected token var ,parsing error unexpected token vscode ,parser error unexpected token var at column 1 in ,parse error unexpected identifier vhdl ,parsing error unexpected token import vue ,parsing error unexpected token eslint vscode ,parsing error unexpected token wix ,parse error syntax error unexpected token while ,parse error syntax error unexpected token while php ,webpack parsing error unexpected token ,wsendpoints parse error unexpected token u in json at position 0 in undefined ,webstorm eslint parsing error unexpected token ,terraform error unexpected token while parsing list ident ,error parsing content unexpected token xpath statement was expected ,how do i fix xml parsing error ,parsing error unexpected token. did you mean ' ' ,parsing error unexpected token expected in react ,parsing error unexpected token expected eslint ,parsing error unexpected token expected eslint typescript ,parsing error unexpected token expected as ,parsing error unexpected token expected as typescript ,parsing error unexpected token expected as string ,parsing error unexpected token expected arrow function ,parsing error unexpected token expected an identifier ,parser error unexpected token expected identifier or keyword at column ,parse error syntax error unexpected token as expecting ,create react app parsing error unexpected token expected ,abstract class parsing error unexpected token expected ,declare parsing error unexpected token expected ,parsing error unexpected token expected extends ,parsing error unexpected token expected eslint prettier/prettier ,error parsing error unexpected token expected ,error parsing error unexpected token expected vue ,enum parsing error unexpected token expected ,parsing error unexpected token. a constructor method accessor or property was expected.eslint ,parsing error unexpected token expected in typescript ,parsing error unexpected identifier expected the token ,parse error unexpected identifier app-id' expected value ,parsing error unexpected token expected json ,js parsing error unexpected token expected ,vuecompilererror error parsing javascript expression unexpected token expected ,syntaxerror error parsing javascript expression unexpected token expected ,parsing error line 1 unexpected token expected ,parse error unexpected identifier in label matching expected string ,parsing error unexpected token expected react native ,rego_parse_error unexpected token expected n or or ,json parse error unexpected token (start_object) expected value_string ,json parse error unexpected token (start_object) expected start_array ,parsing error unexpected token expected prettier/prettier ,parsing error unexpected token expected react typescript ,parsing error unexpected token expected reactjs ,react-scripts parsing error unexpected token expected ,parsing error unexpected token expected servicenow ,parsing error unexpected token expected the token ,parser error unexpected token expected identifier or keyword at the end of the expression ,vuejs parsing error unexpected token expected ,parse error syntax error unexpected '(' expecting variable (t_variable) ,parsing error unexpected token function javascript ,parsing error unexpected token react js ,parsing error unexpected token expected typescript as ,parsing javascript code ,error parsing error unexpected token javascript ,error parsing javascript expression unexpected token ,vue compiler error error parsing javascript expression unexpected token ,parsing error unexpected token in node js ,parsing error unexpected keyword 'this' react ,org.openqa.selenium.javascriptexception javascript error unexpected token ' ' ,parsing error unexpected token var in javascript ,parsing xml file in javascript ,parse error syntax error unexpected token function php ,json parse error unexpected identifier function ,parse error syntax error unexpected token function expecting ) ,error parsing error unexpected token = firebase functions ,parsing error unexpected token function async ,parsing error unexpected token function eslint ,parse error syntax error unexpected token expecting function or const ,parsing error unexpected token for ,async function parsing error unexpected token function ,parse error syntax error unexpected token function in ,error while parsing package ,parse error syntax error unexpected token function ,parse jwt token node js ,parsing xml in node js , , ,a fatal parsing error occurred parsing error unexpected token ,angular eslint parsing error unexpected token ,angular parsing error unexpected token ,arrow function parsing error unexpected token = ,as any parsing error unexpected token expected ,as parsing error unexpected token expected ,await parsing error unexpected token ,aws lambda parsing error unexpected token ,babel parse error unexpected token ,brackets parsing error unexpected token ,class parsing error unexpected token = ,const parsing error unexpected token ,create react app parsing error unexpected token expected ,css parsing error unexpected token ,declare global parsing error unexpected token ,declare namespace parsing error unexpected token ,declare parsing error unexpected token expected ,doctype html parsing error unexpected token ,error handling rpc response error parsing json syntaxerror unexpected token ,error in parse unexpected symbol ,error parsing content unexpected token xpath statement was expected ,error parsing error unexpected token expected ,error parsing error unexpected token javascript ,error parsing error unexpected token vue ,error parsing file unexpected token ,error parsing json response 'unexpected token ' ''. logged in ,error parsing json unexpected token brace. (15360) ,error parsing json unexpected token bracket ,error parsing json unexpected token bracket. (15360) ,error parsing string unexpected token end of file at position 0 ,error parsing time ,error unexpected token in json at position 1 while parsing near ' ,error while parsing json - unexpected token ,error while parsing json - unexpected token in json ,error while parsing json - unexpected token in json at position ,error) parsing sql unexpected token near * * in the following ,eslint html parsing error unexpected token ,eslint optional chaining parsing error unexpected token ,eslint parsing error unexpected token ,eslint parsing error unexpected token = arrow function ,eslint parsing error unexpected token expected ,eslint parsing error unexpected token function ,eslint parsing error unexpected token import ,eslint parsing error unexpected token in typescript cast operator as ,eslint parsing error unexpected token json ,eslint parsing error unexpected token spread operator ,eslint typescript parsing error unexpected token ,firebase parsing error unexpected token = ,godot parser error unexpected token ,how do i fix unexpected token in json error ,how do i fix unexpected token parsing error ,how do i fix xml parsing error ,how to fix parsing error unexpected token ,interface parsing error unexpected token ,java parsing error unexpected token ,javascript parsing error unexpected token ,javascript parsing error unexpected token expected ,js parsing error unexpected token expected ,js_parse_error syntaxerror unexpected token keyword «const» ,json parse error unexpected identifier bad ,json parse error unexpected identifier https ,json parse error unexpected identifier object ,json parse error unexpected identifier ok ,json parse error unexpected identifier tunnel ,json parse error unexpected identifier undefined ,json parse error unexpected token o ,json parse error unexpected token pizza hut ,json parse error unexpected token pizza hut app ,json parse error unexpected token u ,json parsing error unexpected token ,json.parse error unexpected token u in json at position 0 ,json_parsing_error unexpected token end of file at position 0 ,json_parsing_error unexpected token end of file at position 0 in java ,jsx parsing error unexpected token ,keyof parsing error unexpected token expected ,lambda parsing error unexpected token ,lint parsing error unexpected token ,nodejs parsing error unexpected token ,npm install error parsing json unexpected token ,npm parsing error unexpected token ,nuxt parsing error unexpected token ,optional chaining parsing error unexpected token ,package.json error while parsing json - unexpected token in json at position ,parse error syntax error unexpected identifier header ,parse error syntax error unexpected identifier mysql_connect ,parse error syntax error unexpected identifier mysqli_query ,parse error syntax error unexpected token foreach ,parse error syntax error unexpected token global ,parse error syntax error unexpected token match ,parse error syntax error unexpected token match expecting ,parse error syntax error unexpected token match expecting variable ,parse error syntax error unexpected token new ,parse error syntax error unexpected token php ,parse error syntax error unexpected token try ,parse error syntax error unexpected token use ,parse error syntax error unexpected token use php ,parse error syntax error unexpected token var ,parse error syntax error unexpected token while ,parse error syntax error unexpected token while php ,parse error unexpected identifier in label matching expected string ,parse error unexpected identifier vhdl ,parse errors in imported module unexpected token head ,parser error unexpected token '=' at column 2 in 1=$event ,parser error unexpected token '=' ngmodel ,parser error unexpected token = at column 1 in =$event ,parser error unexpected token expected identifier keyword or string ,parser error unexpected token expected identifier or keyword ,parser error unexpected token lexer error ,parser error unexpected token lexer error unexpected character ,parser error unexpected token lexer error unterminated quote ,parser error unexpected token var at column 1 in ,parsing error line 1 unexpected token ,parsing error line 1 unexpected token expected ,parsing error unexpected token ,parsing error unexpected token (fatal) ,parsing error unexpected token . did you mean or ,parsing error unexpected token . optional chaining ,parsing error unexpected token .eslint-plugin-vue ,parsing error unexpected token 1 doctype html ,parsing error unexpected token = ,parsing error unexpected token = (null) ,parsing error unexpected token = arrow function ,parsing error unexpected token = class properties ,parsing error unexpected token = eslint arrow function ,parsing error unexpected token = firebase ,parsing error unexpected token angular ,parsing error unexpected token as.eslint-plugin-vue ,parsing error unexpected token assert eslint ,parsing error unexpected token async eslint ,parsing error unexpected token await ,parsing error unexpected token aws lambda ,parsing error unexpected token axios ,parsing error unexpected token axios eslint ,parsing error unexpected token brackets ,parsing error unexpected token catch servicenow ,parsing error unexpected token colon ,parsing error unexpected token const ,parsing error unexpected token constructor ,parsing error unexpected token css ,parsing error unexpected token data ,parsing error unexpected token db ,parsing error unexpected token declare ,parsing error unexpected token declare global ,parsing error unexpected token doctype ,parsing error unexpected token doctype html ,parsing error unexpected token dot ,parsing error unexpected token dreamweaver ,parsing error unexpected token dynamodb ,parsing error unexpected token else ,parsing error unexpected token eslint ,parsing error unexpected token eslint arrow function ,parsing error unexpected token eslint html ,parsing error unexpected token eslint vscode ,parsing error unexpected token eslint vue ,parsing error unexpected token expected ,parsing error unexpected token expected arrow function ,parsing error unexpected token expected as ,parsing error unexpected token expected from ,parsing error unexpected token expected in react ,parsing error unexpected token expected in react js ,parsing error unexpected token expected javascript ,parsing error unexpected token expected json ,parsing error unexpected token expected keyof ,parsing error unexpected token expected lwc ,parsing error unexpected token expected map ,parsing error unexpected token expected package.json ,parsing error unexpected token expected react ,parsing error unexpected token expected react js ,parsing error unexpected token expected react native ,parsing error unexpected token expected react typescript ,parsing error unexpected token expected reactjs ,parsing error unexpected token expected the token ,parsing error unexpected token expected typescript ,parsing error unexpected token expected vue ,parsing error unexpected token fetch ,parsing error unexpected token for ,parsing error unexpected token function ,parsing error unexpected token function javascript ,parsing error unexpected token glitch ,parsing error unexpected token global ,parsing error unexpected token head ,parsing error unexpected token html ,parsing error unexpected token if ,parsing error unexpected token import ,parsing error unexpected token import at ,parsing error unexpected token import react lazy ,parsing error unexpected token import vue ,parsing error unexpected token in eslint ,parsing error unexpected token in javascript ,parsing error unexpected token in lambda ,parsing error unexpected token in node js ,parsing error unexpected token in react js ,parsing error unexpected token in sap ui5 ,parsing error unexpected token in servicenow ,parsing error unexpected token javascript ,parsing error unexpected token javascript servicenow ,parsing error unexpected token json ,parsing error unexpected token jsx ,parsing error unexpected token lambda ,parsing error unexpected token let ,parsing error unexpected token lint ,parsing error unexpected token lwc ,parsing error unexpected token module ,parsing error unexpected token name ,parsing error unexpected token namespace ,parsing error unexpected token new ,parsing error unexpected token node ,parsing error unexpected token node js ,parsing error unexpected token npm ,parsing error unexpected token of ,parsing error unexpected token optional chaining ,parsing error unexpected token prettier/prettier ,parsing error unexpected token prettier/prettier doctype ,parsing error unexpected token private ,parsing error unexpected token promise ,parsing error unexpected token promise eslint ,parsing error unexpected token python ,parsing error unexpected token question mark ,parsing error unexpected token react ,parsing error unexpected token react function ,parsing error unexpected token react native ,parsing error unexpected token request ,parsing error unexpected token return eslint ,parsing error unexpected token s3 ,parsing error unexpected token salesforce ,parsing error unexpected token sapui5 ,parsing error unexpected token script ,parsing error unexpected token scss ,parsing error unexpected token servicenow ,parsing error unexpected token source ,parsing error unexpected token spread operator ,parsing error unexpected token standard ,parsing error unexpected token switch ,parsing error unexpected token tampermonkey ,parsing error unexpected token template ,parsing error unexpected token throw ,parsing error unexpected token try catch ,parsing error unexpected token ts ,parsing error unexpected token type ,parsing error unexpected token typescript ,parsing error unexpected token ui5 ,parsing error unexpected token useeffect ,parsing error unexpected token user ,parsing error unexpected token var ,parsing error unexpected token vscode ,parsing error unexpected token vue ,parsing error unexpected token vue js ,parsing error unexpected token wix ,parsing error unexpected token zara ,parsing error unexpected token zero ,parsing error unexpected token zerodha ,parsing error unexpected token zlib ,parsing error unexpected token zone.js ,parsing error unexpected token. a constructor method accessor or property was expected ,parsing error unexpected token. did you mean ' ' ,parsing error unexpected token. did you mean ' ' or ,parsing error unexpected token. did you mean ' ' or &rbrace ,prettier html parsing error unexpected token ,react function parsing error unexpected token ,react js parsing error unexpected token expected ,react lazy parsing error unexpected token import ,react map parsing error unexpected token ,react parsing error unexpected token ,react parsing error unexpected token expected ,react typescript parsing error unexpected token expected ,react-scripts parsing error unexpected token expected ,servicenow parsing error unexpected token ,source-reader.karma-typescript error parsing code unexpected token ,syntaxerror json parse error unexpected identifier method ,syntaxerror json parse error unexpected token u ,tampermonkey parsing error unexpected token ,task failed while parsing with following error unexpected token in json at position ,terraform error unexpected token while parsing list ident ,there was an error parsing json data unexpected token in json at position 0 ,try catch parsing error unexpected token ,ts parsing error unexpected token ,typescript parsing error unexpected token expected ,typescript parsing error unexpected token static ,unknown parsing error unexpected token ,useeffect parsing error unexpected token ,vite parsing error unexpected token import ,vscode eslint parsing error unexpected token ,vscode parsing error unexpected token ,vue 3 parsing error unexpected token ,vue cli parsing error unexpected token ,vue js parsing error unexpected token ,vue parsing error unexpected token ,vue parsing error unexpected token expected ,vue parsing error unexpected token import ,vue parsing error unexpected token template ,vue typescript parsing error unexpected token ,webpack parsing error unexpected token ,webstorm eslint parsing error unexpected token ,what causes parsing error ,what does parsing error mean ,what is parsing error unexpected token ,wix parsing error unexpected token ,wsendpoints parse error unexpected token u in json at position 0 in undefined


if( aicp_can_see_ads() ) {

}

by Vladimir Popescu

Being an artist his entire life while also playing handball at a professional level, Vladimir has also developed a passion for all things computer-related. With an innate fascination… read more


Updated on January 31, 2023

  • The cause of unexpected token errors is the incompatibility of the parsers and the coding language.
  • You should have a vast knowledge of JavaScript syntax to understand how to write proper codes.
  • Specifying the parser you want to use can help fix the parsing error: Unexpected token.

The Parsing error unexpected token usually occurs when there is an incompatibility between the parser option and the code. However, in writing JavaScript, developers do come across this error.

This error happens when the development environment is incompatible with the parser’s capabilities. First, we’ll go through the causes of this error and how it often occurs.

As we go further into this article, we’ll guide you through some fixes for the parsing error unexpected token.

What causes the parsing error unexpected token?

When writing a JavaScript application, you can get the error because a specific syntax is missing or added to your code. However, the unexpected token mistake notifies you that JavaScript expects a kind of arrangement in the code you’re writing. An example of what the parsing error unexpected token looks like is:

Nonetheless, you must understand that this error can occur because of different things. JavaScript has expectations.

So, you must know what JavaScript rules and expectations are. Then, it will help you decipher where the issue is.

How can I fix the parsing error unexpected token?

1. Specify the parser you’re using

For ESLint users, you have to specify the parser for ESLint. It is essential because the parser will be able to generate compatible JavaScript syntax that ESLint can read.

A Parser like babel-eslint will be suitable for ESLint. It is because ESLint is not compatible with modern JavaScript syntax. So, you need to specify the parser to use for your configuration.

In the example above, the parser is specific, so ESLint will be able to know what to use. Furthermore, by doing this, you won’t get the parsing error unexpected token ESLint typescript again.

Read more about this topic

  • Windows 11 Advanced Options Missing: How to Get Them Back
  • How to Quickly Change the Drive Letter in Windows 11: 5 Ways
  • How to Merge Folders in Windows 11: 3 Simple Methods

2. Check if your punctuation is incorrect

JavaScript has its syntax, and you must follow the rules that guide it. For example, omitting necessary or adding unknown punctuation marks in your coding will prompt the error.

So, to fix the unexpected token problem, go through your codes for punctuation errors. Punctuation marks like parenthesis and commas must be proper in your coding. If not, JavaScript won’t recognize it and won’t be able to parse it.

In the code above, JavaScript can’t parse it because it expects the parenthesis { to be closed.

3. Check for typos

As said earlier, JavaScript has its syntax. So, its parsers expect every token and symbol to be in a specific order before they can read them.

However, trace your coding to know where the error is from and correct it. Code editors can help you edit your syntax, even before the parser detects it.

It is essential to know the rules of JavaScript syntax and their uses in detail. Then, following the guidelines above, you can fix the parsing error and unexpected token problem.

There are other JavaScript errors that you can come across; visit our page to learn more.

newsletter icon

Newsletter

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

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?

1) Solution

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.

2) Solution

ESLint 2.x experimentally supports ObjectRestSpread syntax, you can enable it by adding the following to your .eslintrc: docs (http://eslint.org/docs/user-guide/configuring#specifying-parser-options)

"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.

3) Solution

"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

4) Solution

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
},
5) Solution

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"
}
6) Solution

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
  }
}
7) Solution

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,
  },
};
8) Solution

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

9) Solution

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

10) Solution

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

"extends": [
    ...,
    "plugin:prettier/recommended"
]
11) Solution

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

12) Solution

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!
13) Solution

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

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

Comments Section

You need to use a parser that supports the object spread property proposal.

That’s not true. ESLint’s default parser Espree does support spread, and even object rest spread (that’s the only experimental feature that espree supports). For more information see this: eslint.org/docs/user-guide/… (http://eslint.org/docs/user-guide/configuring#specifying-parser-options)

You’re right, my original answer only applied to ESLint 1.x, I updated it with info for 2.x

This answer doesn’t add anything to @JaysQubeXon’s answer.

ecmaFeatures has been deprecated. Use ecmaVersion

yarn add -D babel-eslint for those using Yarn.

ecmaVersion: 2018 works without a warning with ESLint 5

Actually it does — you get an example config (with parserOptions included)

For those who don’t know where to add the "parser": "babel-eslint" config statement, it’s in the .eslintrc.json. In my case, it’s a JSON file, but basically, your .eslintrc file

Wast the Unexpected Token «import»? That was my issue.

Note * If you have «ejected» your create-react-app and you are adding eslint-ing to your IDE, babel-eslint is already applied. Just add the parser and your good to go.

I found this article helpful too: grantnorwood.com/…

I don’t see a problem with this solution — it worked fine for me. It’s better than having to install a new package as well!

Great to have the full example++. It helped me to fix a TamperMonkey JS hints error.

@brasofilo where do you change eslint in tamper monkey?

@Metin, go to Dashboard > Settings > Editor > Custom Linter Config

Changing emcaVersion to 2020 did the trick for me when receiving this error for using var?.prop in a React app. Thank you for posting.

👍 However babel-eslint is no longer supported. Use its successor, @babel/eslint-parser. npm i -D @babel/core @babel/eslint-parser then {"parser: "@babel/eslint-parser"}

changing ecmaVersion: 2017 to ecmaVersion: 2020 returned an error: error Parsing error: Invalid ecmaVersion. What else should I do besides changing to 2020?

Instead of changing ecmaVersion: 2017 to ecmaVersion: 2020 I just changed "scripts": { "lint": "eslint ." } to "scripts": { "lint": "eslint" } in the file package.json .

I’m unclear on where you’re suggesting to make these changes. I’d appreciate you taking a look at my ESLint question here since you may be able to answer. Thanks! stackoverflow.com/q/67522592/470749

Your answer could have been helpful if you specified what version wasn’t working and then what version you downgraded to in order to get it working.

You must make these changes to the prettier / prettier rule in your eslint file

babel-eslint is outdated, use @babel/eslint-parser

Works perfect. Also check browser support

Related Topics
javascript
reactjs
eslint

Mentions
Dharman
Pankaj Kumar
Brigand
Vojtech Ruzicka
Dmitry Grinko
Dong Yao
Jays Qube Xon
Kevan Ahlquist
Rajendran Nadar
Alvin Konda
Joee
Cristiano
Alexander Shestakov
Pazu
Asim K T
Pravin Varma

References
36001552/eslint-parsing-error-unexpected-token

Всем привет.
Пишу на реакте, как и рекомендуется в рендере всё упаковываю в один пустой элемент <>
Однако почему то ESLint на нём крашится.

Не могу понять, в чём дело. У кого нибудь было? Как решить?

render() {
    const { open } = this.state;

    return (
      <> //вот тут ошибка.
        <div onClick={this.toggle}>{this.props.children}</div>
        <Modal open={open} toggle={this.toggle}>
             ...
        </Modal>
      </>
    );
  }


  • Вопрос задан

    более трёх лет назад

  • 9247 просмотров

Пригласить эксперта

«Пустой тег» на самом деле является компонентом React.Fragement

Варианты решения проблемы:
1. Использовать полную запись компонента:

return (
  <React.Fragement>
    {/* children */}
  </React.Fragment>
);

2. Установить необходимые модули.

3. Убедиться что конфиг и локальные модули прокинуты в плагин вашей IDE.

Это действительно проблемы чисто PHP Storm. Изкоробочный eslint работет некорректно, не видит всё что нужно, и выдает вот такие ошибки.

Помогла установка плагина ESLint, он видит всё и странных ошибок не выдаёт.
5ce3987a18543855847832.jpeg


  • Показать ещё
    Загружается…

KLBR

Санкт-Петербург

от 130 000 до 180 000 ₽

12 февр. 2023, в 02:07

2000 руб./за проект

12 февр. 2023, в 00:06

1000 руб./в час

11 февр. 2023, в 22:57

25000 руб./за проект

Минуточку внимания

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🎍

Introduction

A common issue that I see when working with front-end JavaScript heavy apps is the dreaded “SyntaxError Unexpected Token in JSON” error! Now this error can be of the form:

SyntaxError: Unexpected token < in JSON at position 0

SyntaxError: Unexpected end of JSON input

syntaxerror: unexpected token '<', "<!doctype "... is not valid json

The error “SyntaxError Unexpected Token in JSON” appears when you try to parse content (for example — data from a database, api, etc), but the content itself is not JSON (could be XML, HTML, CSV) or invalid JSON containing unescaped characters, missing commas and brackets.

There are a few things you can try to fix this error:

  1. Check that the content you are trying to parse is JSON format and not HTML or XML

  2. Verify that there are no missing or extra commas.

  3. Make sure to check for unescaped special characters.

  4. Check for mismatched brackets or quotes.

  5. Make sure the JSON is valid. You can use a tool like JSONLint to validate your JSON and check for any errors.

1. Check that the content you are trying to parse is JSON format and not HTML or XML

A common reason why the error “SyntaxError Unexpected Token in JSON” comes up is that we are trying to parse content that is not even JSON.

Consider the following front-end JavaScript code:

  

fetch('https://localhost:3000/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // Use the data here
  })

In the above example, the fetch() function is being used to retrieve data from a API that returns JSON format — in this case https://localhost:3000/data.

The fetch() function then returns a promise, and when that promise resolves, we handle that with the response.json() method. This just takes our JSON response and converts it to a JSON object to be used!

After that we just console.log out the data object

Now for the server-side of things, look on to our Node JS route that returns the JSON /data

  

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'text/html');  Not returning JSON.
    res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);

We can see that it is setting the Header as text/html. This will give you the error:

syntaxerror: unexpected token '<', "<!doctype "... is not valid json

This is because we are trying to parse the content with JSON.parse() or in our case response.json() and receiving a HTML file!

To fix this, we just need to change the returned header to res.setHeader('Content-Type', 'application/json'):

  

...
var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json'); ✔️ Returning JSON.
    res.end(JSON.stringify({ a: 1 }));
});
...

Whats Content-Type request header anyway?

Pretty much every resource on the internet will need to have a type (similar to how your file system contains file types like images, videos, text, etc).
This is known as a MIME type (Multipurpose Internet Mail Extension)

Browsers need to know what content type a resource is so that it can best handle it. Most modern browsers are becoming good at figuring out which content type a resource is, but its not always 100% correct.

That is why still need to explicitly specify our request header content-type!

syntaxerror: unexpected token ‘<’, “<!doctype “… is not valid json

This error also comes up when your API is returning invalid error pages such as 404/500 HTML pages. Since HTML usually starts with a “less than” tag symbol (<) and JSON is not valid with < tags, it will through this error.

For example, when everything is working find, your node API will happily return JSON. However when it fails with a 500 internal error, it could return a custom HTML error page!
In this case, when you try to do JSON.parse(data) you will get the syntaxerror: unexpected token '<', "<!doctype "... is not valid json.

Additionally, check that you are calling the correct API url. As an example, lets say the API that returns JSON is using the /data route. If you misspelt this, you could be redirected to a 404 HTML page instead!

Tip: Use appropriate error handlers for non-JSON data

If you are using fetch() to retrieve your data, we can add a catch handler to give meaningful error messages to the user:

  

fetch('https://localhost:3000/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // Use the data here
  })
  .catch(error => console.error(error)); /*✔️ Friendly error message for debugging! */

If you are using JSON.parse() we can do this in a try/catch block as follows:

  

try {
    JSON.parse(data);
}
catch (error) {
    console.log('Error parsing JSON:', error, data); /*✔️ Friendly message for debugging ! */
}

JSON objects and arrays should have a comma between each item, except for the last one.

  

{
    "name": "John Smith"
    "age": 30
    "address": {
        "street": "123 Main St"
        "city": "Anytown"
        "state": "USA"
    }
}

This JSON object will throw a “syntaxerror unexpected token” error because there is no comma between “John Smith” and “age”, and also between “Anytown” and “state”.

To fix this, you would add commas as follows:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }
}

By adding commas between each item except for the last one, the JSON object is now in the correct format and should parse without error.

3. Make sure to use double quotes and escape special characters.

JSON strings must be wrapped in double quotes, and any special characters within the string must be properly escaped. Consider the following example:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    },
    "message": "It's a lovely day"
}

When we try to parse this with JSON.parse, we will get the error: SyntaxError: Invalid or unexpected token.

The problem is with the following line using a apostrophe:

"message": "It's a lovely day"

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    },
    "message": "It's a lovely day"
}

As we can see, this will fix our error since we escape the aspostrophe as such:

"message": "It's a lovely day"

4. Check for mismatched brackets or quotes.

Make sure all brackets and quotes are properly closed and match up.

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }

In this example, the JSON object is missing a closing curly bracket, which indicates the end of the object. Because of this, it will throw a “syntaxerror unexpected token” error.

To fix this, you would add the missing closing curly bracket as follows:

  

{
    "name": "John Smith",
    "age": 30,
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "USA"
    }
}

If you want to be sure that the JSON is valid, we can try to use the NPM package JSONLint (https://github.com/zaach/jsonlint)

We can install jsonlint with npm as follows:

  1. Open up the terminal
  2. Run NPM install npm install jsonlint -g
  3. We can then validate a file like so: jsonlint myfile.json

Summary

In this article I went over the SyntaxError: Unexpected token < in JSON at position 0 when dealing with parsing JSON with fetch or JSON.parse. This error is mainly due to the JSON not being in correct format or the content that we are trying to parse is not even JSON.

In the case of JSON being invalid, make sure to check for unescaped characters, missing commas, non-matching brackets and quotes.

To be really sure, check the JSON with tools like JSONLint to validate!

In the case of the content you are trying to parse being non-JSON such as HTML, check your API to make sure that error pages return JSON correctly instead of HTML pages.

Понравилась статья? Поделить с друзьями:
  • Ошибка p2a03 инфинити
  • Ошибка parsec 15000
  • Ошибка p2a03 infiniti fx35
  • Ошибка park бмв х5 е70
  • Ошибка p2a00 хонда цивик 5д