ESLint in React: Parsing error: Unexpected token = [duplicate] - javascript

This question already has answers here:
Why does ESLint not recognize my class arrow functions?
(2 answers)
Unexpected token "=" reported while running eslint on arrow functions
(1 answer)
Closed last year.
I'm getting this error:
error Generating development JavaScript bundle failed 92:7 error
Parsing error: Unexpected token =
I am using gatsby & a custom eslintrc:
{
"parser": "babel-eslint", // uses babel-eslint transforms
"parserOptions": {
"sourceType": "module",
"ecmaVersion": 2020,
"ecmaFeatures": {
"jsx": true,
"modules": true
}
},
"settings": {
"react": {
"version": "detect" // detect react version
}
},
"env": {
"node": true, // defines things like process.env when generating through node
"browser": true,
"es6": true
},
"extends": [
"eslint:recommended", // use recommended configs
"plugin:react/recommended"
]
}
I found solutions to this problem in several places, but none of it worked. The most common solution I found was "parser": "babel-eslint" to the eslintrc file. But I already have that. Don't know what I can try anymore.
The files this error occurs in are usually files written in an older style React, but I don't know why they shouldn't work anymore?
For example:
class Post extends Component {
constructor(props) {
super(props)
this.state = {
isVisible: true,
isOpen: false,
}
this.toggleIsVisible = this.toggleIsVisible.bind(this)
this.toggleModal = this.toggleModal.bind(this)
}
toggleIsVisible = () => { <=== HERE ESLINT COMPLAINS ABOUT THE FIRST, DEFINING EQUALS-SIGN
this.setState({ isVisible: !this.state.isVisible })
}
Another piece of code eslint doesn't like is this, in a different file:
try {
await Function(values)
} catch { <==== ESLINT DOESNT LIKE THIS OPEN BRACKET, SIMILAR ERROR MESSAGE: "Unexpected token {"
setFormState('error')
}
I have also tried disabling the line in eslint as well as the full file, but didn't work either. Oh, and when I chuck eslint out completely, everything works fine and I can run as well as build my project.

Related

React in vscode not linting errors properly?

I recently changed my laptop and every day I find a new problem and no solution. I used to create a react app and if I forgot to return the jsx in a react component, I would see in chrome something like "Error: App(...) Nothing was returned from render .... etc. Don't remember if there was an error in vscode but I would swear there was too.
Now, I do that on porpuse, created a fresh react app with npx create-react-app and removed the return from App and do a console log in the component function. When I npm start, I can see the console log in dev tools, no error in vscode, no error in chrome. Just white screen and the terminal doesn't show any errors either!
In other projects I always use eslint + prettier + airbnb but tried to remove everything (except the plugins in vscode from eslint and prettier) and did a fresh create-react-app with nothing, same result, so I assume that's not the problem.
Also, I would like to also ask if my eslint config has any issue or everything is fine? Would you modify anything? Mostly for react.
Another problem, when I add "prettier/prettier": "error" in eslintrc to see all prettier errors, it forces me to do double quotes, even though my extension says single quotes and my .prettierrc file also do singleQuote true. The only solution is to remove the eslintrc rule but I can't see prettier errors anymore.
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"plugin:react/recommended",
"airbnb",
"airbnb/hooks",
"prettier",
"plugin:jsx-a11y/recommended",
"plugin:react-hooks/recommended"
],
"parser": "#babel/eslint-parser",
"parserOptions": {
"requireConfigFile": false,
"babelOptions": {
"presets": ["#babel/preset-react"]
},
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 13,
"sourceType": "module"
},
"plugins": ["prettier", "react", "react-hooks"],
"rules": {
"prettier/prettier": "error",
"react/function-component-definition": [
"error",
{ "namedComponents": "arrow-function" }
]
}
}

Why does ESLint not recognize my class arrow functions?

I followed the advice on How do I configure ESLint to allow fat arrow class methods which states to set the parser to babel-eslint.
I installed it and updated my config file as follows:
{
"parserOptions": {
"parser": "babel-eslint",
"ecmaVersion": 12,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"semi": "error",
"indent": ["error", 2],
"eqeqeq": ["error", "always"],
"max-depth": ["error", 5],
"space-before-function-paren": ["error", "never"],
"template-curly-spacing": ["error", "always"],
"quotes": ["error", "single", { "allowTemplateLiterals": true }],
"curly": "error",
"brace-style": ["error", "1tbs"],
"space-before-blocks": "error"
}
}
However it is still breaking eslint, giving a parsing error as follows:
class Person {
constructor() {
console.log(this);
this.hello1();
this.hello2();
}
// breaks eslint, but WHY?
hello1 = () => {
console.log(this);
}
hello2() {
console.log(this);
}
}
const P1 = new Person();
It is highlighting the first = and saying:
Parsing Error
unexpected token =
How can I troubleshoot this further? ESLint is correctly applying all the rules in this file, but seems to ignore the parser options.
Or something else?
I'm not sure if this is relevant here:
https://github.com/babel/babel-eslint#note-babel-eslint-is-now-babeleslint-parser-and-has-moved-into-the-babel-monorepo
but I don't really know what that means.
I think you are getting that linting error because you are not using ECMA version 2022 (aka ECMA latest). Please check this link at shorturl.at/nsAS5 that shows no lint errors on the fat arrow class method because ECMA version is at latest 2022. When you change ECMA version to 2021 or lower, you get the Parsing Error unexpected token = error.
Also, I notice some things about your eslintrc.json:
I think it might be because babel-eslint is deprecated? https://www.npmjs.com/package/babel-eslint. Maybe you should try #babel/eslint-parser? https://www.npmjs.com/package/#babel/eslint-parser
your config looks a bit off. you should place parser key outside of parserOptions key like so:
"parser": "babel-eslint",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
see https://eslint.org/docs/user-guide/configuring/language-options
also, I just want to point out that eslint by default uses espree as its parser, but you can use esprima or #babel/eslint-parser (or #typescript-eslint/parser if you're using typescript) see https://eslint.org/docs/user-guide/configuring/plugins
Your configuration file is not correct:
This line here:
"parser": "babel-eslint",
is doing nothing. Unfortunately it will not throw an error and continue to use the default parser.
Once you do this you can begin to use the babel parser if the rest of the dependencies are correctly installed.

How to extend CRA ESLint rules with EXTEND_ESLINT environment variable

Recently Facebook's Create React App (CRA) released a new feature which allows you to extend their base ESLint rules.
We recognise that in some cases, further customisation is required. It
is now possible to extend the base ESLint config by setting the
EXTEND_ESLINT environment variable to true.
Setting Up Your Editor
Here is the example given but with no detail such as filename or what "shared-config" is.
{
"eslintConfig": {
"extends": ["react-app", "shared-config"],
"rules": {
"additional-rule": "warn"
},
"overrides": [
{
"files": ["**/*.ts?(x)"],
"rules": {
"additional-typescript-only-rule": "warn"
}
}
]
}
}
The feature is enabled by added an environment variable.
EXTEND_ESLINT=true
but on the documentation page it also doesn't give any information how to use it - Advanced configuation
I've added their example code to my build in a file called .eslintrc.json but I get a build error:
"Error: ESLint configuration in .eslintrc.json is invalid: - Unexpected top-level property "eslintConfig"."
Has anyone got this working? Does the file need to export a module?
While unclear from the Create-React-App documentation, the example they give is as if the project's ESLint configuration was inside the eslintConfig property of the package.json file.
You need to configure ESLint as described in its documentation. So if you choose the .eslintrc.json way, it must be a valid ESLint configuration file, which doesn't have a eslintConfig property.
The only things that matter in the example are:
they're extending from "react-app" before any other configuration
any additional rule is set to "warn" to avoid stopping the project from building
if using TypeScript, place the specific TS related configuration in the "overrides" section.
A simple .eslintrc.js (notice the extension) configuration file for a CRA project using TypeScript could be as follows:
const defaultRules = [
'react-app',
'eslint:recommended',
// any other plugins or custom configuration you'd like to extend from.
];
module.exports = {
parser: '#typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
},
env: {
browser: true,
node: true,
es6: true,
jest: true,
},
extends: defaultRules,
rules: {
'array-callback-return': 'warn',
'consistent-return': 'warn',
'default-case': 'warn',
// etc.
},
overrides: [
{
files: ['**/*.ts', '**/*.tsx'],
plugins: ['#typescript-eslint'],
extends: [
...defaultRules,
'plugin:#typescript-eslint/recommended',
// any other TypeScript specific config (from a plugin, or custom)
],
rules: {
'#typescript-eslint/no-explicit-any': 'warn',
'#typescript-eslint/no-unused-vars': 'warn',
'#typescript-eslint/no-unused-expressions': 'warn',
// etc.
},
},
],
settings: {
react: {
// React version. "detect" automatically picks the version you have installed.
version: 'detect',
},
},
};

How can I fix ESLint Parsing Error for unexpected token "/"?

const Index = () => (
<div>
<p>Hello World</p>
<Link href="/posts">
<a>Posts</a>
</Link>
</div>
)
ESLint is returning a Parsing Error (Unexpected token) for the closing </p> tag. What am I missing? Are normal HTML attributes not allowed in JSX? (The div seems to work fine)
The exact error is:
[eslint] Parsing error: Unexpected token "/"
ESLint is installed
ESLint React is installed
ESLint React is configured in .eslintrc.json
EDIT:
Using VS Code (with ESLint plugin)
Partial .eslintrc.json:
"env": {
"browser": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true
},
"sourceType": "module"
},
"plugins": [
"react"
],
"rules": {
...
}
I received a similar error in Visual Studio 2017 (not Code).
The error "ESLint encountered a parsing error" occurred at the beginning of an import statement.
janniks' solution did not work for me. I suspect because "es6: true "enable[s] all ECMAScript 6 features except for modules".
Since I'm using TypeScript, I don't want to use babel-eslint, per Sean's answer (though it did resolve the parsing error in a plain JS file).
The key trade-off can be summarized as: babel-eslint supports
additional syntax which TypeScript itself does not, but
typescript-eslint supports creating rules based on type information,
which is not available to babel because there is no type-checker.
Instead, I continued to use "#typescript-eslint/parser". Below is my minimal working .eslintrc:
{
"parser": "#typescript-eslint/parser",
"parserOptions": {
"sourceType": "module"
},
"rules": {
"quotes": [ "error", "single" ]
}
}
Note: The error was resolved in plain JS files (not TS) even if I removed the "parser" line, therefore using the default eslint parser.
I encountered the same issue today while setting up a new React project. The fix that worked for me was installing the babel-eslint package (npm install babel-eslint --save-dev or yarn add babel-eslint -D). I then added "parser": "babel-eslint" to my .eslintrc config file. This seems to help babel and ESLint get along a little better than using the default parser.
I'm not sure what caused the problem, but this solved it for me. I changed the .eslintrc.json to the following:
{
//"env": {
// "browser": true,
// "commonjs": true,
// "es6": true
//},
"extends": [
"standard",
"standard-react"
]
}
I left in my original rules as well.
This problem seems to have multiple different causes, so check out the other answers as well.

Why eslint does not check JS?

Eslint loads, but does not fix 'problem js'...
File eslint.config.json
{
"ecmaFeatures": {
"jsx": true
},
"env": {
"browser": true,
"node": true,
"jquery": true
},
"rules": {
"quotes": 0,
"no-trailing-space": 0,
"eol-last": 0,
"no-unused-vars":0,
"no-underscore-dangle":0,
"no-alert": 0,
"no-lone-blocks": 0
},
"globals": {
jQuery: true,
$ : true
}
}
In JS file i can use global variables...
Lint does not check JS.
If you are using version newer then 1.0.0 none of the rules are enabled by default. Since your config above only shows disabling rules, that means eslint runs with no enabled rules, and as such, doesn't find any errors. What you might want to do is add the following line to your config:
{
"extends": "eslint:recommended"
}
which will enabled all of the rules marked as recommended on this page.
Or you can also extend from existing configs that you can find on NPM by searching for eslint-config-
I had same issue. Adding below line in the .eslintrc helped:
"extends": ["eslint:recommended", "plugin:react/recommended"]
Note: extends option might be already there but without the plugin option.

Categories