Screen shot of error message

ESLint: “Parsing error: Unexpected token” in Visual Studio Code

While adding the plumbing for a new JavaScript website project, I knew it needed an ESLint config to keep my code linted and clean. So I installed ESLint the usual way:

npm i eslint --save-dev
npx eslint --init

Note: The npx command requires [email protected].  Alternatively you can run ./node_modules/.bin/eslint –init.

After being prompted with a few questions to customize my install, I went along my merry way creating files and writing some modern ES6 and ES7 code.  However, the ESLint plugin in Visual Studio Code was giving me odd errors like this in my React JSX code:

  • Parsing error: Unexpected token = 
  • Parsing error: Unexpected token { 
  • Parsing error: Unexpected token / 
Screen shot of error message

The solution

Unexpected token  errors are caused by incompatibilities in your parser options and the code you’re writing.  In this case, I’m using a number of ES6 language features like arrow functions, destructured variables, and such.

The solution is to specify the parser to use in our ESLint configuration – babel-eslint.  Because ESLint doesn’t support the more modern JavaScript syntax, we need to use the babel-eslint  plugin to automatically export a compatible version of our code that ESLint can read.

Here’s an example of my .eslintrc.json  file with the appropriate parser  specified:

{
    "extends": "airbnb",
    "parser": "babel-eslint", // This line is required to fix "unexpected token" errors
    "rules": {
        "indent": ["warn", 4],
        "react/jsx-indent": ["warn", 4, { "checkAttributes": true}],
        "react/react-in-jsx-scope": "off",
        "react/destructuring-assignment": "off",
        "no-nested-ternary": "warn",
        "react/prop-types": "warn"
    }
}

Note: Your ESLint configuration file may also be named .eslintrc , or .eslintrc.js , or .eslint.yml  depending on the format of your config file.

And that’s how I fixed that.  Simple, yeah?  Well it took me an hour to figure it out, so I hope this post helps you fix it faster than I did!