I want use decorators in my react project and there is an error just show out.I had read a lot of docs for this, but it’s not help.This has been bothering me for a long time., please help me.
My project used: create-react-app + craco + eslint.
There is some configs in my files:
package.json:
{
"name": "xxx",
"version": "0.1.0",
"private": true,
"dependencies": {
"@craco/craco": "^5.6.4",
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "craco start",
"build": "craco build",
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@babel/plugin-proposal-decorators": "^7.10.5",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.10.4",
"@babel/plugin-proposal-optional-chaining": "^7.10.4",
"@babel/plugin-transform-regenerator": "^7.10.4",
"@babel/plugin-transform-runtime": "^7.10.5",
"@commitlint/cli": "^8.1.0",
"babel-eslint": "10.1.0",
"cz-conventional-changelog": "^2.1.0",
"eslint-config-airbnb": "^18.2.0",
"eslint-plugin-import": "^2.22.0",
"eslint-plugin-jsx-a11y": "^6.3.1",
"eslint-plugin-react": "^7.20.3"
}
}
craco.config.js:
eslint: {
enable: true /* (default value) */,
mode: 'file',
},
babel: {
// presets: ['react-app'],
plugins: [
'@babel/plugin-transform-runtime',
[
'@babel/plugin-proposal-decorators',
{
'legacy': true
}
],
'@babel/plugin-transform-regenerator',
'@babel/plugin-proposal-optional-chaining',
'@babel/plugin-proposal-nullish-coalescing-operator'
],
},
.eslintrc.js:
module.exports = {
root: true,
env: {
'es6': true,
'browser': true,
'commonjs': true
},
extends: ['airbnb', 'react-app'],
globals: {
Babel: true,
React: true
},
parserOptions: {
ecmaVersion: 2020,
parser: 'babel-eslint',
sourceType: 'module'
},
};
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
83.2k19 gold badges163 silver badges170 bronze badges
asked Mar 15, 2016 at 2:19
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
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
},
answered Sep 26, 2019 at 19:59
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 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
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
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 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_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
CristianoCristiano
1342 silver badges4 bronze badges
I solved this problem by setting this in .eslintrc.json file:
"extends": [
...,
"plugin:prettier/recommended"
]
Dharman♦
29.3k21 gold badges80 silver badges131 bronze badges
answered Sep 1, 2021 at 8:55
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
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
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:
- I deleted
$HOME/.nvm
folder which was not deleted when I removednvm
earlier. - Verified node is the latest and did proper parser options.
- It started working!
answered Oct 8, 2019 at 11:47
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
1
I’m using typescript and I solve this error change
parser
....
"prettier/prettier": [
"error",
{
.....
"parser": "typescript",
.....
}
],
....
answered Apr 28, 2021 at 9:36
2
.
.
{
"parserOptions": {
"ecmaVersion": 2020
},
.
.
Will do the trick.
answered Nov 14, 2022 at 7:09
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 SopherPhilip Sopher
4872 gold badges5 silver badges18 bronze badges
Содержание
- Parsing error: Unexpected character ‘@’. #313
- Comments
- Parsing error unexpected character
- ошибка разбора ошибки: неожиданный символ ‘`’
- ошибка разбора ошибки: неожиданный символ ‘`’
- ошибка синтаксического анализа eslint: неожиданный символ ‘#’
- вавилон-эслинт
- ошибка синтаксического анализа непредвиденный символ машинописный текст eslint
- eslint браузер
- Неожиданный токен eslint es6
- расширение неожиданного токена eslint
- Parsing error: Unexpected token, expected «;» while trying to lint JSON files #11593
- Comments
- How To Fix – “Parsing error: Unexpected Token” in React.js or Javascript ?
- How To Fix – “Parsing error: Unexpected Token” in React.js or Javascript ?
- Primitive Check:
- [ESLint] Parsing error: unexpected token =>
- What is this article about?
- Project environment & full configuration
- When did this error appear?
- How did it solve?
- Reason
- Solution steps
- Summary
- Top comments (2)
- 11 Tips That Make You a Better Typescript Programmer
- 1 Think in Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead. #2 Understand declared type and narrowed type One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type. Источник
- #2 Understand declared type and narrowed type
Parsing error: Unexpected character ‘@’. #313
I have the error: Parsing error: Unexpected character ‘@’. I am not sure what is wrong.
the code is:
import ui from ‘redux-ui’;
@ui(<>)
my configuration is:
<
«parser»: «babel-eslint»,
«extends»: [«eslint:recommended», «plugin:react/recommended»],
«env»: <
«es6»: true,
«browser»: true,
«node»: true
>,
«plugins»: [«react»],
«parserOptions»: <
«ecmaVersion»: 6,
«sourceType»: «module»,
«ecmaFeatures»: <
«modules»: true,
«jsx»: true
>
>,
«rules»: <
«eqeqeq»: [2, «allow-null»],
«jsx-quotes»: 2,
«react/display-name»: 2,
«react/jsx-curly-spacing»: [2, «never»],
«react/self-closing-comp»: 2,
«react/jsx-indent-props»: [2, 2],
«react/jsx-no-duplicate-props»: 2,
«no-console»:0,
«strict»: 0
>
>
I am using this plugins and presets:
presets: [«es2015», «react», «stage-0»],
«plugins»: [«babel-plugin-transform-decorators-legacy», «transform-runtime»]
The text was updated successfully, but these errors were encountered:
i seem to be experiencing similar, but it seemed to have cropped up recently.
yes is recently the error for me.
It’s probably the same as #311, etc.
There is currently a regression in ESLint 2.10.0. Pin to ESLint 2.9.x for now until there’s a bug fix (or try 2.10.1)
eslint 2.9.0 works!
eslint 2.10.1 doesn’t work.
pinning to eslint 2.9.0 didn’t help me.
in my case, npm run lint works, but npm run build-dev doesn’t work 😢
so must be something around webpack, it seems like babel-eslint isn’t running at all because i’m getting errors on async, decorators and class-vars (in both jsx and js files alike fwiw):
here is a relevant snippets from relevant files (edited for brevity) (i also tried with both node 5.8.0 and 6.1.0 , but same).
can anyone spot anything fishy or different about my setup than a working one.
Источник
Parsing error unexpected character
15.12.2022 153 Просмотры
eslint configuration: .eslintrc.json
ошибка разбора ошибки: неожиданный символ ‘`’
ошибка разбора ошибки: неожиданный символ ‘`’
Ошибка 1:1 Ошибка синтаксического анализа: непредвиденный символ ‘ ‘ 1 проблема (1 ошибка, 0 предупреждений) npm ERR! код ELIFECYCLEnpm ERR! errno 1npm ОШИБКА! functions@1.0.0 lint: `eslint .`npm ERR! Состояние выхода 1npm ERR!npm ERR! Ошибка в functions@1.0.0 lint script.npm ERR! Вероятно, это не проблема с npm.
Вы можете отключить синтаксические ошибки HTML с помощью параметров. См. спецификацию WHATWG HTML, чтобы узнать подробности синтаксических ошибок HTML. Только non-void-html-element-start-tag-with-trailing-solidus по умолчанию отключен, поскольку Vue.js поддерживает самозакрывающиеся теги.
Повторение назначения и синтаксиса JSON, а также подробное изучение JSON Parse SyntaxError в JavaScript.
ошибка синтаксического анализа eslint: неожиданный символ ‘#’
Закрыть Присоединяйтесь к GitHub сегодня. GitHub является домом для более чем 50 миллионов разработчиков, которые вместе размещают и рецензируют код, управляют проектами и создают программное обеспечение.
вавилон-эслинт
вавилон-эслинт. babel-eslint позволяет анализировать ВЕСЬ корректный код Babel с помощью фантастического ESLint. Критическое изменение в v11.xx Начиная с версии v11.xx, babel-eslint теперь требует Babel в качестве одноранговой зависимости и ожидает существования допустимого файла конфигурации Babel. Это гарантирует, что одна и та же конфигурация Babel используется как во время линтинга, так и во время компиляции.
Настройка ESLint. ESLint спроектирован так, чтобы его можно было полностью настраивать, то есть вы можете отключить каждое правило и запускать только с базовой проверкой синтаксиса или смешивать и сопоставлять связанные правила и ваши собственные правила, чтобы сделать ESLint идеальным для вашего проекта.
ошибка синтаксического анализа непредвиденный символ машинописный текст eslint
Ключевой компромисс можно резюмировать следующим образом: babel-eslint поддерживает дополнительный синтаксис, которого нет в самом TypeScript, но typescript-eslint поддерживает создание правил, основанных на информации о типе, которая недоступна для babel из-за отсутствия проверки типов.
eslint браузер
ESLint статически анализирует ваш код, чтобы быстро найти проблемы. ESLint встроен в большинство текстовых редакторов, и вы можете запускать ESLint как часть конвейера непрерывной интеграции.
Чтобы помочь людям с самого начала писать код, совместимый со стандартами, и не тратить время на проверку кода, в базу кода был добавлен набор файлов конфигурации ESLint, чтобы JavaScript можно было анализировать автоматически. Этот автоматический линтинг может происходить либо во время написания кода, либо в редакторе кода, либо при использовании командной строки.
ESLint — это инструмент для выявления шаблонов, обнаруженных в коде ECMAScript/JavaScript, и составления отчетов о них. Во многом он похож на JSLint и JSHint за несколькими исключениями: ESLint использует Espree для анализа JavaScript. ESLint использует AST для оценки шаблонов в коде.
Для удобства ESLint предоставляет ярлыки, предварительно определяющие глобальные переменные, предоставляемые популярными библиотеками и средами выполнения. Это правило поддерживает эти среды, перечисленные в разделе «Указание сред». Несколько примеров приведены ниже.
Неожиданный токен eslint es6
Интеграция с VS Code прерывается: первое = подчеркивается этим сообщением: [eslint] Ошибка синтаксического анализа: неожиданный токен =. Линтинг прерывается для всего файла, никаких других ошибок не отображается, хотя они и существуют, а автоисправление при сохранении не работает.
расширение неожиданного токена eslint
Неожиданный токен возвращает 1 проблему (1 ошибка, 0 предупреждений). eslintrc уже недостаточно для конкретных ситуаций, таких как использование. 1, это было нормально экспортировать класс Root по умолчанию, расширяет React. Uncaught SyntaxError: Unexpected token Не запускайте сразу же stackoverflow. Добавьте раздел плагинов и укажите eslint-plugin-jsdoc в качестве плагина.
запретить сбивающие с толку многострочные выражения (no-unexpected-multiline) Свойство “extends”: “eslint:recommended” в файле конфигурации включает это правило. Точки с запятой обычно необязательны в JavaScript из-за автоматической вставки точки с запятой (ASI). Вы можете требовать или запрещать точку с запятой с помощью полуправила.
ESLint — это линтер JavaScript, который можно использовать для линтинга кода TypeScript или JavaScript. В этом посте мы рассмотрим, как настроить linting в вашем проекте.
Источник
Parsing error: Unexpected token, expected «;» while trying to lint JSON files #11593
Tell us about your environment
- ESLint Version: 5.16.0
- Node Version: 10.13.0
- npm Version: 6.9.0
What parser (default, Babel-ESLint, etc.) are you using?
babel-eslint
Please show your full configuration:
What did you do? Please include the actual source code causing the issue, as well as the command that you used to run ESLint.
What did you expect to happen?
the lint returns no error
What actually happened? Please include the actual, raw output from ESLint.
it returns an error:
Are you willing to submit a pull request to fix this bug?
The text was updated successfully, but these errors were encountered:
Hi @slim-hmidi , thanks for this issue.
It seems that you’re trying linting JSON files, but I think babel-eslint doesn’t support that.
@g-plane Before I added it I used the default parser and I got this error.
@slim-hmidi The default parser only supports JavaScript (not JSON) as well. I think this is working as designed, although I understand your frustrations here.
I think you would need to look for a parser that supports JSON and converts it to ESTree for ESLint to consume. I don’t know of one off the top of my head.
I found this parser eslint-plugin-json but I don’t know if it the suitable one.
@platinumazure the eslint-plugin-json fixs my problem. But if the default parser parses only the js files and we could lint a json extension with —ext option, we should modify the default parser to take a consideration the json files or add a plugin to parse them in the eslint configuration.
I don’t find it normal to add json extension when lint files then I discover the default parser does not do the job. Maybe I said stupid things but I think by default it should parse all the allowed extensions.
@slim-hmidi ESLint allows any file extension to be specified. While ESLint’s core parser and linting rules are designed for JavaScript, we intentionally designed ESLint to be pluggable. Parsers and plugins can be used to extend ESLint’s functionality beyond pure JavaScript files.
I can understand how it might seem unintuitive when you’re starting out and trying different CLI options; but the behavior you’ve observed is in line with the design and architecture of ESLint.
Unfortunately, it looks like there wasn’t enough interest from the team
or community to implement this change. While we wish we’d be able to
accommodate everyone’s requests, we do need to prioritize. We’ve found
that issues failing to reach accepted status after 21 days tend to
never be accepted, and as such, we close those issues.
This doesn’t mean the idea isn’t interesting or useful, just that it’s
not something the team can commit to.
Thanks for contributing to ESLint and we appreciate your understanding.
Источник
How To Fix – “Parsing error: Unexpected Token” in React.js or Javascript ?
How To Fix – “Parsing error: Unexpected Token” in React.js or Javascript ?
In this post, we will explore – How To Fix – “Parsing Error: Unexpected Token” in React.
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.
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.
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.
- Go to the .eslintrc (or .eslintrc.json) config file and make the below changes.
Also check what value you have in “.babelrc”.
If above doesn’t work, you could also try,
- If applicable, go to your package.json file and check the below.
- 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.
- You can also try changing the ecmaVersion in the .eslintrc.json file.
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-
Источник
[ESLint] Parsing error: unexpected token =>
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.
Exit fullscreen mode
Exit fullscreen mode
Project environment & full configuration
ESLint Version: ^7.15.0
Node Version: v12.18.2
npm Version: 6.14.5
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
Exit fullscreen mode
- Add «parser» config in .eslintrc.js
Exit fullscreen mode
- Remove unnecessary config for non-React project
Exit fullscreen mode
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🎍
Damn it, why do I always forget the parser. Thanks.
It happens often to me too 😅
Glad it helped!
For further actions, you may consider blocking this person and/or reporting abuse
11 Tips That Make You a Better Typescript Programmer
1 Think in
Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.
Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.
#2 Understand declared type and narrowed type
One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.
Источник