Explain Codes LogoExplain Codes Logo

Eslint Parsing error: Unexpected token

javascript
eslint
parser-options
ecmascript
Nikita BarsukovbyNikita Barsukov·Oct 6, 2024
TLDR

To quickly resolve the Unexpected token error in ESLint, set the parser to '@babel/eslint-parser' in your .eslintrc:

{ "parser": "@babel/eslint-parser" // Like hiring a guide for a jungle journey }

And, ensure that the ecmaVersion declared matches your JS syntax:

{ "parserOptions": { "ecmaVersion": 2020 // Like setting your _time machine_ to the correct year } }

This alignment of ESLint with your code's syntax helps you avoid token parsing black holes.

ESLint parsing essentials

The issues thrown by ESLint, such as Unexpected token, often stem from a mismatch between your code syntax and what ESLint can parse. An updated parser and correct ecmaVersion typically resolve this.

ESLint, ECMAScript, and Time Travelling

To keep up with ever-evolving JavaScript, your .eslintrc configuration should tell ESLint the ECMAScript version you're using - a bit like setting coordinates for a time-travel machine.

Embracing Syntax Evolution

If your JavaScript leverages modern syntax like object rest-spread, ESLint needs a heads-up:

{ "parserOptions": { "experimentalObjectRestSpread": true // ESLint, engage Ultra Instinct mode! } }

Tackling common ESLint parsing challenges

Compatible Pairings

For those using React 16.3 or higher, be aware of changes, especially to the Context API, and ensure your ESLint configuration is in sync.

Engaging Advanced Syntax Support

Using @babel/eslint-parser is ideal if you're dabbling with React or ES6+ syntax.

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

Parser Installation

npm install @babel/eslint-parser --save-dev # OR yarn add -D @babel/eslint-parser

Handling Legacy Projects

For projects with older versions of ESLint (1.x), switch to babel-eslint.

{ "parser": "babel-eslint" // Like asking Gandalf for help in a Hobbit journey }