Eslint parsing error the keyword import is reserved

React — Parsing error: The keyword ‘import’ is reserved React is a free and open source Javascript library that helps us build interactive user interfaces. It is well suitable for building SPAs (Single Page Applications) and the best thing is that its components are reusable. In Visual Studio Code I get Parsing error: The […]

Содержание

  1. React — Parsing error: The keyword ‘import’ is reserved
  2. 0. A minimal, complete and verifiable example
  3. 1. Parsing error: The keyword ‘import’ is reserved
  4. 2. Visual Studio Code? – Other text editors or IDE:s?
  5. 3. Configuration files of my reproducible example
  6. 4. Is this question a duplicate?
  7. 4a. How is ESLint integrated into Create React App?
  8. 4b. Do any of the answers of the other question solve my question?
  9. 5. Other reports of the error
  10. References
  11. Answers
  12. References
  13. 0. Prerequisites
  14. 1. Locally install ESLint
  15. 2. Create a .eslintrc.json file that works
  16. Update all npm packages to their latest versions
  17. Conclusion
  18. References
  19. ESLint sort imports
  20. Prerequites
  21. Install
  22. Config
  23. Problem
  24. Solution
  25. sort-imports
  26. eslint-plugin-simple-import-sort
  27. Getting Prettier, Eslint and Vscode to work together
  28. Wait what are Eslint and Prettier?
  29. Prerequisites
  30. Install Vscode plugins
  31. Install dependencies
  32. Setup the config files
  33. Enable formatOnSave in Vscode
  34. Try it out

React — Parsing error: The keyword ‘import’ is reserved

React is a free and open source Javascript library that helps us build interactive user interfaces. It is well suitable for building SPAs (Single Page Applications) and the best thing is that its components are reusable.

In Visual Studio Code I get Parsing error: The keyword ‘import’ is reserved .

What actions would you recommend to remedy this error?

0. A minimal, complete and verifiable example

I provide my .eslintrc.json and package.json files below.
However, they will likely not be sufficient to reproduce the error.
So here is a link to a zip file containing all the necessary project files.

To locally install the project, run npm install . – This may take about 5-9 minutes. 1
Then npm start should open the project in the default web browser. 2

When I do this and hit F12 , I get no errors but two warnings in the console of the browser.

The warnings are:

‘unUsedArgument’ is defined but never used. Allowed unused args must match /^_/u no-unused-vars , and

‘unUsedVariable’ is assigned a value but never used. Allowed unused vars must match /^_/u no-unused-vars .

1. Parsing error: The keyword ‘import’ is reserved

The error in the title has nothing to do with my choice of text editor.
This is easy to confirm by running ESLint from the command line.

2. Visual Studio Code? – Other text editors or IDE:s?

The error, Parsing error: The keyword ‘import’ is reserved , also shows up when I open App.js in VS Code.

Although I am using Visual Studio Code, I invite answers (and discussions) of other text editors and IDE:s as well. Note that – in addition to installing ESLint correctly via npm – you also have to install a plugin/extension for your specific integrated development environment (IDE).
In my case, I use the official VS Code ESLint extension. 3

Still, the focus here should clearly be on the npm command and on the installation of Node.js packages.

3. Configuration files of my reproducible example

4. Is this question a duplicate?

I believe my question is not a duplicate of that question.

The origin of the package.json of my question comes from a Create React App via the command
npx create-react-app .

The package.json of the other question is missing the react-scripts npm package which every Create React App must have. The other question is clearly not about Create React App, whereas my question is. 4

4a. How is ESLint integrated into Create React App?

As this answer explains, a Create React App depends directly on the react-scripts package.

The react-scripts package in turn depends on the eslint-config-react-app package, which in turn depends on the @babel/eslint-parser package. I will come back to the latter below.

4b. Do any of the answers of the other question solve my question?

In summary, the key criterion for if a question is a duplicate is if any of the answers to the other question provides a solution to my own question.

So the key question is if there is such an answer.

First of all, the highest voted answer is obsolete in that it suggests to install the deprecated babel-eslint package. The authors of that package explicitly instruct to use the successor package @babel/eslint-parser instead of babel-eslint .

Installing the deprecated babel-eslint package would be even more problematic in my Create React App example, since @babel/eslint-parser is already installed. I cannot accept a suggestion to simultaneously install two different versions of the ESLint Parser (of which one is deprecated).

The accepted answer is not relevant in my case, as I installed ESLint only locally (not globally).

For all the other answers I tried the suggested solutions on my reproducible example, one by one. Most of them resulted in a different error message than mine, but none of them solved my question – contrary to the two self-answers I have posted below.

Although the error messages are identical in the two questions – the reasons for why they occur are obviously significantly different. I conclude that my question is not a duplicate of Parsing Error The Keyword import is Reserved (SublimeLinter-contrib-eslint).

5. Other reports of the error

In references 18-24 of the list below, I link some previous reports of the error here – or similar errors. Some of those links (questions) are likely related to the issue here, but possibly not all of them.

References

2 In my case Google Chrome Version 98.0.4758.102, 64-bit. Running on Windows 10.

3 Apart from installing the extension, I have added «eslint.nodePath»: «C:\Program Files\nodejs», to my (user) settings.json file in VS Code. No other changes.

4 I have added the create-react-app tag to my question.

Answers

There are 2 suggested solutions here and each one has been listed below with a detailed description. The following topics have been covered briefly such as Reactjs, Create React App, Npm, Eslint. These have been categorized in sections for a clear and precise explanation.

Here is simple solution – just move the rules attribute from .eslintrc.json to the eslintConfig attribute of package.json . 1

And don’t keep .eslintrc.json . Just delete it! 2

The package.json file will now be as follows.

Check to see that you were successful.
Use the first line if you are on Microsoft Windows (backslashes).
Use the second line if you are on Linux or macOS (forward slashes).

If your text editor (VS Code in my case) is still open, make sure that you restart it before you expect to see the error go away!

References

1 I got the idea from this post.

2 Don’t run npm init @eslint/config either.
The error(s) will persevere if you don’t delete .eslintrc.json !

3 A. If you suspect that you may have a global installation of ESLint, first run:
npm uninstall eslint —global

B. If you have already run npm install – as suggested on line 6 in the question – then you should not need to run npm install eslint —save-dev to install ESLint.
Because the first npm install also installs ESLint, as I discovered when writing this answer.

0. Prerequisites

If the server is running, close it by hitting Ctrl + C .

I strongly recommend uninstalling any global installations of ESLint.
To see what global packages are installed, in the command line run: 1

If ESLint is globally installed, uninstall by running:

To correctly install ESLint into your local project, I recommend performing the following two steps.

Locally install ESLint.

Create a functioning .eslintrc.json file.

As it turns out, you will also need to do a third step.

  1. Update all npm packages to their latest versions.

1. Locally install ESLint

To locally install ESLint, run: 2

at the end of package.json .

2. Create a .eslintrc.json file that works

NOTE! Before moving on, do yourself a favor by saving a copy of your current .eslintrc.json file, as the next command will destroy (recreate) that file.

To create a new .eslintrc.json file, run:

You will be asked a number of questions, to which I answer by pressing Enter to choose the default, except for the format which I choose to be JSON (instead of JavaScript ).

In addition to creating the .eslintrc.json file, this will also add the «eslint-plugin-react»: «^7.29.2» attribute under devDependencies to the package.json file. 3

The command npm init @eslint/config destroys the existing .eslintrc.json file, so you will have to manually add back any «rules» or other JSON settings that you want to keep.
In this case, I add back the rules that were in the original .eslintrc.json .
The result is as below.

Now when I open VS Code, instead of an error there are two warnings, which is exactly the desired outcome.

Great! But wait – unfortunately there turns out to be a fly in the ointment. The problem is that, when I now run npm start to open the project in the web browser and hit F12 , two errors show up in the console.
The error messages are:

  • Uncaught ReferenceError: process is not defined , and
  • Line 0: Parsing error: ImportDeclaration should appear when the mode is ES6 and in the module context .

Luckily, I have already posted a solution to this problem, namely:
Update all npm packages to their latest versions.
The section below is a bit succinct, so if you want more flesh on the bones, go visit that other answer.

Update all npm packages to their latest versions

Consider updating all npm packages to their latest versions.
The purpose is to decrease the risk of getting version conflicts.
The advice to update all packages has also been put forth in this answer.

A. Globally install npm-check-updates

In the command line, run:

B. Update package.json to contain the latest versions

The following command will write the latest package version numbers to your package.json :

Here is what it looks like in Windows 10:

C. Install the latest versions

In the command line, run:

D. Check for errors in the browser and/or in the terminal

In the command line, run:

Both the browser and the terminal now displays five errors.

Discomforting, eh?

Yes definitely! – But don’t give up hope! Just close the server ( Ctrl + C ) and try it over and over again.
Yesterday when I got these errors, all I needed to do was to run npm start one more time.
Today I tried running npm start 4-5 more times, but still got the errors.
So I tried npm install && npm start twice, and finally it ran without errors.
Not sure what is going on. Maybe some time has to pass before it works?

Finally there are no errors in the browser.

And the terminal says Compiled successfully!

Conclusion

Following the steps above helped me remedy the error in the question title:
Parsing error: The keyword ‘import’ is reserved.

For a project with settings even slightly different, 5 just copy-pasting from the .eslintrc.json file above is unlikely to work.
Running npm init @eslint/config and upgrading all packages is more likely to be successful.

References

1 I am on Windows 10, but I expect all the commands provided here to work just as fine on both Linux and macOS.

2 A. Expect this command to take about 5-10 minutes to complete.
B. As long as your source code is not transformed by Babel, there is no reason to install @babel/eslint-parser . Just normal eslint should be enough. See When should I use @babel/eslint-parser ?
If you are using TypeScript, then you will need @babel/eslint-parser .
The command to install is:
npm install eslint @babel/core @babel/eslint-parser —save-dev
The npm init @eslint/config configuration command should be used in the same way as for the normal (non[email protected]) ESLint.

3 The «eslint-plugin-react» attribute in package.json does not seem to be of much relevance though.

4 The two warnings still show up in the text editor – just as they should.

5 For example, you might be using Angular or Vue instead of React.

Источник

ESLint sort imports

Oct 4, 2021 • Blog • Edit

This article goes over how to sort imports with ESLint.

Prerequites

Install

Install eslint with npm:

Your package.json should look like:

Config

Create an ESLint config:

Your .eslintrc will look like:

Execute the eslint binary with npx:

Or create a package.json script:

To call it from the command line:

If you encounter the parsing error:

Update your .eslintrc with the following:

Problem

Let’s say you have the index.js :

As more modules are imported, it can get messy. So how can we enforce a sorting order without having to do it manually each time? With ESLint.

Solution

sort-imports

ESLint has the rule sort-imports . To enable it in .eslintrc :

But when you run eslint , you’ll get the errors:

Autofixable errors can be fixed by passing —fix in the CLI:

This fixes the member sort error, as shown in the diff below:

But the declaration sort error still persists. This is because changing the evaluation order of imported modules may lead to unexpected changes in how the code works (see #11542).

As a result, there’s no automatic fix for this rule. You’ll either need to manually fix it or ignore the sorting of import declaration statements like below:

This isn’t ideal so what can you do? You can find other ESLint plugins that handle import sorting.

eslint-plugin-simple-import-sort

One ESLint plugin that performs autofixable import sorting is eslint-plugin-simple-import-sort .

Источник

Getting Prettier, Eslint and Vscode to work together

For quite a while I’ve tried getting Prettier, Eslint and Vscode to work together, but never found a solution that satisfied me. Now, as I’m working on a new React project in my day job, I finally found some time to make it work.

Wait what are Eslint and Prettier?

Eslint is a javascript linter that can help you find syntax or other errors. Eslint can be extended by plugging in pre-defined configs or completely configuring it yourself. Paired with the plugin for vscode, it can show you errors as you type.

Prettier is a code formatter for quite a few languages, including javascript. You can have code being automatically or optionally formatted with it.

Prerequisites

I assume you have basic knowledge about NPM and Vscode, as I won’t cover it here. You need to have:

  • Vscode installed
  • NodeJS and NPM installed

Install Vscode plugins

First of all install the Vscode plugins ESLint and Prettier — Code formatter and make sure they’re enabled.

Install dependencies

Exit fullscreen mode

Setup the config files

Create an .eslintrc file in your project root.

In here we basically tell Eslint to:

  • Extend from the recommended prettier config
  • Register the Prettier plugin we installed
  • Show Prettier errors as errors

Exit fullscreen mode

Note: Your eslint config can include many more rules. I’m keeping it simple and easy to grasp.

Next create a .prettierrc file in your project root.

You can tweak these settings, or add new ones as you like:

Exit fullscreen mode

Enable formatOnSave in Vscode

Look for formatOnSave and check the checkbox, or add this line to settings.json :

Exit fullscreen mode

Try it out

If you kept the .prettierrc file like above, Vscode should now:

  • indent your code with 2 spaces
  • use single quotes instead of double
  • add semicolons add the end of each line

If you’re having trouble try restarting Vscode.

Источник

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account

Comments

@jeff1evesque

I’ve installed the following within my .travis.yml:

...
  - npm install -g eslint babel-eslint
  - npm install -g eslint-plugin-react
...

However, implementing eslint on my jsx templates, generate the following traceback errors, from my travis ci:

...
$ eslint . --ext=jsx -c test/config/eslint.json

/home/travis/build/jeff1evesque/machine-learning/src/jsx/import/general/spinner.jsx

  13:16  error  Parsing error: Unexpected token <

/home/travis/build/jeff1evesque/machine-learning/src/jsx/import/general/submit.jsx

  17:16  error  Parsing error: Unexpected token <

/home/travis/build/jeff1evesque/machine-learning/src/jsx/import/input-data/supply_dataset_file.jsx

  86:13  error  Parsing error: Unexpected token <

/home/travis/build/jeff1evesque/machine-learning/src/jsx/import/input-data/supply_dataset_url.jsx

  79:13  error  Parsing error: Unexpected token <

/home/travis/build/jeff1evesque/machine-learning/src/jsx/import/input-data/supply_predictors.jsx

  52:13  error  Parsing error: Unexpected token <

/home/travis/build/jeff1evesque/machine-learning/src/jsx/import/result/result_display.jsx

  23:17  error  Parsing error: Unexpected token <

/home/travis/build/jeff1evesque/machine-learning/src/jsx/import/session-type/data_append.jsx

  13:1  error  Parsing error: The keyword 'import' is reserved

/home/travis/build/jeff1evesque/machine-learning/src/jsx/import/session-type/data_new.jsx

  10:1  error  Parsing error: The keyword 'import' is reserved

/home/travis/build/jeff1evesque/machine-learning/src/jsx/import/session-type/model_generate.jsx

  66:13  error  Parsing error: Unexpected token <

/home/travis/build/jeff1evesque/machine-learning/src/jsx/import/session-type/model_predict.jsx

  10:1  error  Parsing error: The keyword 'import' is reserved

/home/travis/build/jeff1evesque/machine-learning/src/jsx/select_session.jsx

  10:1  error  Parsing error: The keyword 'import' is reserved

✖ 11 problems (11 errors, 0 warnings)

The command "eslint . --ext=jsx -c test/config/eslint.json" exited with 1.
...

This is strange, because nothing substantial has changed in my jsx templates. And just last week, my eslint, had no problems linting within my travis ci. Perhaps latest changes within this repo, has broke my linting process?

Note: travis ci build logs can be reviewed, to see when eslint refused to accept my jsx syntax.

thescientist13, about0, hubeiyichangzy, sankhaKarunasekara, Annie-Huang, giovannibenussi, Moongazer, cesards, spector32, tutv3, and ann-kilzer reacted with thumbs up emoji

This was referenced

Feb 16, 2016

@jeff1evesque

Even though the eslint fails, with the above copied traceback, from my travis ci implementation, doing a manual vagrant up, on my repository:

  • https://github.com/jeff1evesque/machine-learning

yields a fully functional project (on the master branch). So, the eslint generates the above errors, even though my react jsx templates, are working as I intend.

@ljharb

For one, React needs to be in scope for jsx to work, and you aren’t requiring React in any of those files.

@jeff1evesque

For one, React needs to be in scope for jsx to work, and you aren’t requiring React in any of those files.

My react is working fine. I did a fresh build off a vagrant up. All my jsx eventually ends up as minified javascript. I’m not using require(), if that’s what you’re wondering. I’m using es6’s import / export. Nevertheless, I haven’t figured out yet, why my travis ci has suddenly broke, with respect to eslint.

@jeff1evesque

The following is my eslint.json configuration, used via eslint, within .travis.yml:

/**
 * eslint.json: this file provides a configuration of rules that eslint will
 *              implement, to validate 'jsx' files, when imported via the
 *              '-c [path/to/eslint.json]' flag.
 *
 * Note: eslint rules, and options are available:
 *
 *       https://github.com/yannickcr/eslint-plugin-react#configuration
 *       http://eslint.org/docs/rules/
 */
{
    "plugins": [
        "react"
    ],
    "ecmaFeatures": {
        "jsx": true,
        "modules": true
    },
    "rules": {
        "react/display-name": 1,
        "react/forbid-prop-types": 1,
        "react/jsx-boolean-value": 1,
        "react/jsx-closing-bracket-location": 1,
        "react/jsx-curly-spacing": 1,
        "react/jsx-handler-names": 1,
        "react/jsx-indent-props": 1,
        "react/jsx-key": 1,
        "react/jsx-max-props-per-line": 1,
        "react/jsx-no-bind": 1,
        "react/jsx-no-duplicate-props": 1,
        "react/jsx-no-literals": 1,
        "react/jsx-no-undef": 1,
        "react/jsx-pascal-case": 1,
        "react/jsx-quotes": 1,
        "react/jsx-sort-prop-types": 1,
        "react/jsx-sort-props": 1,
        "react/jsx-uses-react": 1,
        "react/jsx-uses-vars": 1,
        "react/no-danger": 1,
        "react/no-did-mount-set-state": 1,
        "react/no-did-update-set-state": 1,
        "react/no-direct-mutation-state": 1,
        "react/no-multi-comp": 1,
        "react/no-set-state": 1,
        "react/no-unknown-property": 1,
        "react/prefer-es6-class": 1,
        "react/prop-types": 1,
        "react/react-in-jsx-scope": 1,
        "react/require-extension": 1,
        "react/self-closing-comp": 1,
        "react/sort-comp": 1,
        "react/wrap-multilines": 1
    }
}

@yannickcr

npm install -g eslint babel-eslint

Seems your problem come from here.

By doing this you are always installing the latest ESLint release, which can introduce some breaking changes if a new major version is released… and this is what happened a few days ago with the release of ESLint 2.0.0.

Since ESLint 2.0.0 the parser options format changed (migration guide), so with your current configuration the JSX/module support is not enabled.

You should replace

"ecmaFeatures": {
    "jsx": true,
    "modules": true
}

by

"parserOptions": {
    "ecmaFeatures": {
        "jsx": true,
        "modules": true
    }
}

Another solution is to use babel-eslint instead of the ESLint default parser (you are installing it but it is not used in your .eslintrc config file), for this add the following line in your .eslintrc

Generally speaking you should at least fix the major versions of your dependencies to avoid future breaking changes, for example:

...
  - npm install -g eslint@1.x.x babel-eslint@4.x.x
  - npm install -g eslint-plugin-react@3.x.x
...
Keysox, charlielow, Vilvarin, cwjcsu, ianberdin, pmadruga, pansy199211, arman-mukatov, samjeffress, epszaw, and 193 more reacted with thumbs up emoji
kleinfreund, safinsingh, ArtturiSipila, Debzou, and amits7204 reacted with thumbs down emoji
aaqibkhaan, steffanhalv, rodrigooler, andrew528i, appsparkler, mohseenrm, IMRahulSaini, AlirezaRahi, meetparikh94, zcmgyu, and 11 more reacted with laugh emoji
MTayyabSaeed, aaqibkhaan, robinkwilson, ITpandaffm, micahstubbs, steffanhalv, rodrigooler, andrew528i, appsparkler, mohseenrm, and 19 more reacted with hooray emoji
wongjiahau, jaredwilli, bshyong, rrousselGit, sqxone, aaqibkhaan, davidsonsns, steffanhalv, rodrigooler, kunokdev, and 25 more reacted with heart emoji
arifinoid, 2zovd, iamr0man, 6thpath, NazarGorokhivskiy, m-khosrojerdi, Terkwood, chloerice, henriquehbr, and RidhikGovind reacted with rocket emoji

This was referenced

Feb 16, 2016

@jeff1evesque

@yannickcr, works, thank you! I will be implementing your additional suggestion, by installing all my package dependencies, at major versions.

@hybrisCole

Got the same problem and tried this:

"parserOptions": {
      "ecmaVersion": 7,
      "sourceType": "module",
      "ecmaFeatures": {
          "jsx": true,
      }
  },

Did not want to go with the babel-eslint fix because I’m using react native I think that’s an unnecesary extra step to transpile it.

zxiest, jhalvorson, noyobo, zhengminhui, ucwaldo, viraths, elderbas, markhorgan, UtkarshGupta-CS, janaagaard75, and 82 more reacted with thumbs up emoji
ArouiniLobna, OoDeLally, theotherdon, tondi, auek, brunorcunha, and JohnCasab reacted with hooray emoji
brunorcunha and JohnCasab reacted with heart emoji
adabedi, maxk096, brunorcunha, and JohnCasab reacted with rocket emoji

@yannickcr

babel-eslint does not transpile your code, it just allow you to use the Babel parser (Babylon) instead of ESLint default one (Espree) to parse your code.

But can you post your full .eslintrc config file, the code that trigger the error and the eslint/eslint-plugin-react versions ? Thanks.

@hybrisCole

Yup that’s true hehe, sorry about the misconception.

Here’s my .eslint:

{
  "parserOptions": {
      "ecmaVersion": 7,
      "sourceType": "module",
      "ecmaFeatures": {
          "jsx": true,
      }
  },
  "plugins": [
    "react",
    "react-native"
  ],
  "extends": ["eslint:recommended", "plugin:react/recommended"],
  "rules": {
    "comma-dangle" : 0,
    "react-native/no-unused-styles": 2,
    "react-native/split-platform-components": 2,
  },
  "settings": {
    "react": {
      "pragma": "React",
      "version": "0.14.8"
    }
  },
}

Here’s my package.json:

{
  "name": "InternetTent",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "lint": "eslint *.js",
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "dependencies": {
    "axios": "0.9.1",
    "react": "0.14.8",
    "react-native": "0.23.1"
  },
  "devDependencies": {
    "eslint": "2.7.0",
    "eslint-plugin-react": "4.3.0",
    "eslint-plugin-react-native": "1.0.0"
  }
}

So I’m basically learning React Native and wanted it to add eslint to my project, the code that fails is the tutorial code from React Native:

import React, {
  AppRegistry,
  Component,
  Image,
  StyleSheet,
  ListView,
  Text,
  View
} from 'react-native';
import { get } from 'axios';

I added "sourceType": "module", in the .eslintrc and import keyword error stopped happening,

Regards,

dmi3y, adoji92, monicao, nicosommi, rmnegatives, dawsbot, ifthenelse, mmayla, burkeholland, tamj0rd2, and 23 more reacted with thumbs up emoji
ubaid4j, aptlyundecided, and a1exlism reacted with heart emoji

@landed1

I am using webpack like this :

{ test: /.jsx?$/, exclude: /(node_modules|bower_components)/, include:"./src/", loader: 'babel', query: { presets: ['react', 'es2015', 'stage-0'], plugins: [ 'transform-runtime', 'transform-decorators-legacy', 'transform-object-rest-spread' ], cacheDirectory: true } }

Do we need 2 files ?
.eslint
.eslintrc

an where do both live ? I am hoping for project root.I am almost there with linting JSX in .js files in my react project its just failing to spot the

Clarity would be most welcome TY

@ljharb

@landed1

@dhirajg27

In .eslintrc replace

"ecmaFeatures": {
    "jsx": true,
    "modules": true
}

with

  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true,
      "modules": true,
      "experimentalObjectRestSpread": true
    }
MoronVV, sapegin, cainaf, mritterhoff, piyushchauhan2011, xgqfrms-GitHub, tamj0rd2, gamingumar, malangaveuday, chantlong, and 8 more reacted with thumbs up emoji

@ghost

I’ve tried the different versions of your configurations without success. But I follow this simple tutorial and it works, I hope it can helps you. 😄
Getting eslint right in React Native

@viraths

"parserOptions": {
      "sourceType": "module",
      "ecmaFeatures": {
          "jsx": true,
      }
  }

ecmaVersion is optional

@ljharb

I think ecmaVersion does need to be 6 or higher, but sourceType module probably sets that.

@xgqfrms-GitHub

// redux constants

export const PAGE_SIZE = 3;

// [eslint] Parsing error: The keyword 'export' is reserved

.eslintrc

{
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true,
            "modules": true,
            "experimentalObjectRestSpread": true
        }
    },
    "plugins": [
        "react"
    ],
    "extends": ["eslint:recommended", "plugin:react/recommended"],
    "rules": {
        "comma-dangle": 0
    },
    "settings": {
        "react": {
            "pragma": "React",
            "version": "15.4.2"
        }
    }
}
xgqfrms-GitHub, AndrewFinlay, dfrho, perevezencev, xyzdata, naveenkumardot25, davepoon, xgqfrms, angelitolm, hrdyjan1, and tutv3 reacted with thumbs up emoji
shri3k, yumemi-higashi, and odragora reacted with thumbs down emoji
xgqfrms and angelitolm reacted with laugh emoji
xyzdata and xgqfrms reacted with hooray emoji
xyzdata, Youth8, and xgqfrms reacted with heart emoji
xgqfrms reacted with rocket emoji
xgqfrms and vintagexav reacted with eyes emoji

@ljharb

@xgqfrms-GitHub That’s really related to eslint core, and not eslint-plugin-react, so I’m not sure why you posted that here.

@xgqfrms-GitHub

@ljharb

I just find this place by using google, and it works for me!
You know that somebody may also have this problem, so I think it will help by leaving a note.

@ljharb

Your note doesn’t explain how the problem was fixed — it just provides an eslintrc and a warning that can’t appear if that eslintrc is used, that core eslint’s docs would fix, and that has nothing to do whatsoever with this repo.

@xyzdata

@piperchester

@hybrisCole ‘s suggestion worked for me — had to restart to Atom to pick up the changes 😅

@odm275

I’m having this same issue.VScode’s finds some eslint configuration that comes when you use create-react-app, and I’m getting this error. Any help is appreciated.

@MikeTheCanuck

@odm275 can you post your full .eslintrc config file (if any), the specific error that’s being thrown, the code that trigger the error and the eslint/eslint-plugin-react versions? [Heck, a link to the repo in question wouldn’t hurt either.]

I’ve been using VSCode as my editor for a React project that I originally generated from create-react-app, and I’ve more or less gotten eslint wrangled into submission. You can see my setup here if that would help. It’s possible you’ve installed the ESLint VSCode Extension or similar, which may be part or all of the source of the issue.

@golinmarq

I got the same error [eslint] Parsing error: The keyword 'import' is reserved and here it is my .eslintrc. I don’t know what could it be

{
  "plugins": [
    "react"
  ],
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true,
      "modules": true,
      "experimentalObjectRestSpread": true
    }
  },
  "env": {
    "es6": true,
    "browser": true,
    "node": true,
    "mocha": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended"
  ],
  "rules": {
    "strict": [2, "safe"],
    "no-debugger": 2,
    "brace-style": [
      2,
      "1tbs",
      { "allowSingleLine": true }
    ],
    "no-trailing-spaces": 2,
    "keyword-spacing": 2,
    "space-before-function-paren": [
      2,
      "never"
    ],
    "spaced-comment": [2, "always"],
    "vars-on-top": 2,
    "no-undef": 2,
    "no-undefined": 2,
    "comma-dangle": [2, "never"],
    "quotes": [2, "single"],
    "semi": [2, "always"],
    "guard-for-in": 2,
    "no-eval": 2,
    "no-with": 2,
    "valid-typeof": 2,
    "no-unused-vars": 2,
    "no-continue": 1,
    "no-extra-semi": 1,
    "no-unreachable": 1,
    "no-unused-expressions": 1,
    "no-magic-numbers": 1,
    "max-len": [1, 80, 4],
    "react/prefer-es6-class": 1
  }

@ljharb

I’m not sure, but that’s an eslint issue, not an issue with this plugin.

micolaprs

added a commit
to micolaprs/comblabel
that referenced
this issue

Jun 20, 2019

@micolaprs

@kselax

I added to the .eslintrc and it doesn’t help
{ "parserOptions": { "ecmaVersion": 7, "sourceType": "module", "ecmaFeatures": { "jsx": true, } }, "rules": { "semi": ["error", "always"], "quotes": ["error", "double"], } }

Annie-Huang

added a commit
to Annie-Huang/pluralsight-redux-app-used-to-build-script-update2019
that referenced
this issue

Aug 11, 2019

@Annie-Huang

@jmalik001

«parser»: «babel-eslint» in .eslintrc.json solved my problem

@ljharb

eslint has fixed its issue anyways.

@kmmbvnr

Fixed by setting ecmaVersion and sourceType

  "eslintConfig": {
    "extends": "google",
    "parserOptions": {
      "ecmaVersion": 7,
      "sourceType": "module"
    }
  }

@ajzawawi

sourceType: «module» works. If you’re using VSCode or Atom, restarting the editor after making the change helps. It should pick it up after.

@cagross

This comment has been minimized.

@ljharb

This comment has been minimized.

@cagross

This comment has been minimized.

@hammerhai

Did anyone try this with their .eslintrc.js?

module.exports = {
  "extends": [
    "eslint:recommended",
  ],
  "parser": "babel-eslint"
};

I did that and it works perfectly fine for using something like import * as firebase from 'firebase/app'

@amir-mustafa

This comment has been minimized.

0. Prerequisites

If the server is running, close it by hitting
Ctrl+C.

I strongly recommend uninstalling any global installations of
ESLint.
To see what global packages are installed, in the command line run:
1

npm list --global --depth 0

If ESLint is globally installed, uninstall by running:

npm uninstall eslint --global

To correctly install ESLint into your local project, I recommend
performing the following two steps.

  1. Locally install ESLint.

  2. Create a functioning .eslintrc.json file.

As it turns out, you will also need to do a third step.

  1. Update all npm packages to their latest versions.

1. Locally install ESLint

To locally install ESLint, run:
2

npm install eslint --save-dev

This will add

  ,
  "devDependencies": {
    "eslint": "^7.32.0"
  }

at the end of package.json.

2. Create a .eslintrc.json file that works

NOTE! Before moving on, do yourself a favor by saving a copy of your
current .eslintrc.json file, as the next command will destroy
(recreate) that file.

To create a new .eslintrc.json file, run:

npm init @eslint/config

You will be asked a number of questions, to which I answer by pressing
Enter to choose the default, except for the format
which I choose to be JSON (instead of JavaScript).

Configuring ESLint

In addition to creating the .eslintrc.json file, this will also add
the "eslint-plugin-react": "^7.29.2" attribute under
devDependencies to the package.json file.
3

The command npm init @eslint/config destroys the existing
.eslintrc.json file, so you will have to manually add back any
"rules" or other JSON settings that you want to keep.
In this case, I add back the rules that were in the original
.eslintrc.json.
The result is as below.

.eslintrc.json :

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:react/recommended"
  ],
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": [
    "react"
  ],
  "rules": {
    "no-unused-vars": [
      "warn",
      {
        "argsIgnorePattern": "^_",
        "varsIgnorePattern": "^_"
      }
    ]
  }
}

Now when I open VS Code, instead of an error there are two warnings,
which is exactly the desired outcome.

VS Code now displaying two warnings but no errors

Great! But wait – unfortunately there turns out to be a fly in the
ointment.
The problem is that, when I now run npm start to open the project in
the web browser and hit F12, two errors show up in the
console.
The error messages are:

  • Uncaught ReferenceError: process is not defined, and
  • Line 0: Parsing error: ImportDeclaration should appear when the mode is ES6 and in the module context.

Luckily, I have already posted a solution to this problem, namely:
Update all npm packages to their latest versions.
The section below is a bit succinct, so if you want more flesh on the
bones, go visit that other answer.

Update all npm packages to their latest versions

Consider updating all npm packages to their latest versions.
The purpose is to decrease the risk of getting version conflicts.
The advice to update all packages has also been put forth in
this answer.

A. Globally install npm-check-updates

In the command line, run:

npm install --global npm-check-updates

B. Update package.json to contain the latest versions

The following command will write the latest package version numbers to
your package.json:

npm-check-updates --upgrade

Here is what it looks like in Windows 10:

Upgrading package.json

C. Install the latest versions

In the command line, run:

npm install

D. Check for errors in the browser and/or in the terminal

In the command line, run:

npm start

Both the browser and the terminal now displays five errors.

Discomforting, eh?

Yes definitely! – But don’t give up hope!
Just close the server (Ctrl+C) and try it over
and over again.
Yesterday when I got these errors, all I needed to do was to run
npm start one more time.
Today I tried runningnpm start 4-5 more times, but still got the
errors.
So I tried npm install && npm start twice, and finally it
ran without errors.
Not sure what is going on. Maybe some time has to pass before it works?

Finally there are no errors in the browser.

NO errors in the web browser!

And the terminal says Compiled successfully!

The terminal says: 'Compiled successfully!'

Yay!
4

Conclusion

Following the steps above helped me remedy the error in the question
title:
Parsing error: The keyword ‘import’ is reserved.

For a project with settings even slightly different,5 just
copy-pasting from the .eslintrc.json file above is unlikely to
work.
Running npm init @eslint/config and upgrading all packages is more
likely to be successful.

A note about deleting package-lock.json and node_modules

I wholeheartedly embrace a frequent use of the npm install command.
As soon as there is a change to package.json or any other
configuration file – such as .eslintrc.json – the npm install
command should immediately be run.

By contrast, I have never ever seen anything gained by deleting the
package-lock.json file and/or the node_modules directory.
6

So my recommendation is: don’t delete any file or directory,
just run npm install.

References

  • npm – get a list of globally installed packages
  • Installation of ESLint using npm
  • Start using @eslint/config in your project
  • When should I use @babel/eslint-parser?
  • Update all npm packages to their latest versions
  • Update all current packages to their lastest versions
  • npm-check-updates – documentation

1 I am on Windows 10, but I expect all the commands
provided here to work just as fine on both Linux and macOS.

2
A. Expect this command to take about 5-10 minutes to complete.
B. As long as your source code is not transformed by Babel,
there is no reason to install @babel/eslint-parser.
Just normal eslint should be enough.
See When should I use @babel/eslint-parser?
If you are using TypeScript, then you will need
@babel/eslint-parser.
The command to install is:
npm install eslint @babel/core @babel/eslint-parser --save-dev
The npm init @eslint/config configuration command should be used
in the same way as for the normal (non[email protected]) ESLint.

3 The "eslint-plugin-react" attribute in package.json
does not seem to be of much relevance though.

4 The two warnings still show up in the text editor –
just as they should.

5
For example, you might be using Angular or Vue instead of React.

6 Every time you delete node_modules, you will pay a
penalty cost of 5-10 minutes of your precious time.

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Eslint parsing error the keyword const is reserved
  • Es проводник ошибка аутентификации при копировании
  • Es проводник ошибка аутентификации google диск
  • Errors loadsettings ошибка
  • Errors load settings ошибка

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии