Eslint parsing error the keyword export is reserved

What code were you trying to parse? I'm trying to use typescript-eslint, and I followed the Getting Started page. Unfortunately, I'm having problems to make the parser identify very basic T...

What code were you trying to parse?

I’m trying to use typescript-eslint, and I followed the Getting Started page. Unfortunately, I’m having problems to make the parser identify very basic TypeScript/JS keywords, like export.

Please see https://github.com/flisboac/ts-promise-scheduler for the project in question. The error is:

./ts-promise-scheduler/src/index.ts
  1:1  error  Parsing error: The keyword 'export' is reserved

✖ 1 problem (1 error, 0 warnings)

My .eslint.js is configured as such:

module.exports = {
    root: true,
    parser: '@typescript-eslint/parser',
    plugins: [
        '@typescript-eslint',
    ],
    extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/eslint-recommended',
        'plugin:@typescript-eslint/recommended',
    ],
    parserOptions: {
        tsconfigRootDir: "./",
        project: "tsconfig.module.json",
    },
};

And here are the first lines of the affected file

export enum JobStatus {
    PENDING,
    RUNNING,
    RESOLVED,
    REJECTED,
    CANCELED,
};

// ...

What did you expect to happen?

To accept export as a keyword, as per named/default export in TypeScript and the ES6+ standards, in the context of exporting declarations.

What actually happened?

export seems to be identified as a reserved name, regardless of context. Parsing fails.

Versions

Disclaimer:I’m using yarn.

package version
@typescript-eslint/parser 2.16.0
TypeScript 3.7.4
ESLint 6.8.0
node 12.13.0
npm 6.12.0
yarn 1.21.1

Output of yarn versions`:

yarn versions v1.21.1
{
  yarn: '1.21.1',
  'ts-promise-scheduler': '1.0.0',
  node: '12.13.0',
  v8: '7.7.299.13-node.12',
  uv: '1.32.0',
  zlib: '1.2.11',
  brotli: '1.0.7',
  ares: '1.15.0',
  modules: '72',
  nghttp2: '1.39.2',
  napi: '5',
  llhttp: '1.1.4',
  http_parser: '2.8.0',
  openssl: '1.1.1d',
  cldr: '35.1',
  icu: '64.2',
  tz: '2019a',
  unicode: '12.1'
}

Output of yarn list:

yarn list v1.21.1
├─ @babel/code-frame@7.8.3
│  └─ @babel/highlight@^7.8.3
├─ @babel/highlight@7.8.3
│  ├─ chalk@^2.0.0
│  ├─ esutils@^2.0.2
│  └─ js-tokens@^4.0.0
├─ @types/eslint-visitor-keys@1.0.0
├─ @types/json-schema@7.0.4
├─ @typescript-eslint/eslint-plugin@2.16.0
│  ├─ @typescript-eslint/experimental-utils@2.16.0
│  ├─ eslint-utils@^1.4.3
│  ├─ functional-red-black-tree@^1.0.1
│  ├─ regexpp@^3.0.0
│  ├─ regexpp@3.0.0
│  └─ tsutils@^3.17.1
├─ @typescript-eslint/experimental-utils@2.16.0
│  ├─ @types/json-schema@^7.0.3
│  ├─ @typescript-eslint/typescript-estree@2.16.0
│  └─ eslint-scope@^5.0.0
├─ @typescript-eslint/parser@2.16.0
│  ├─ @types/eslint-visitor-keys@^1.0.0
│  ├─ @typescript-eslint/experimental-utils@2.16.0
│  ├─ @typescript-eslint/typescript-estree@2.16.0
│  └─ eslint-visitor-keys@^1.1.0
├─ @typescript-eslint/typescript-estree@2.16.0
│  ├─ debug@^4.1.1
│  ├─ eslint-visitor-keys@^1.1.0
│  ├─ glob@^7.1.6
│  ├─ is-glob@^4.0.1
│  ├─ lodash@^4.17.15
│  ├─ semver@^6.3.0
│  └─ tsutils@^3.17.1
├─ acorn-jsx@5.1.0
├─ acorn@7.1.0
├─ ajv@6.10.2
│  ├─ fast-deep-equal@^2.0.1
│  ├─ fast-json-stable-stringify@^2.0.0
│  ├─ json-schema-traverse@^0.4.1
│  └─ uri-js@^4.2.2
├─ ansi-escapes@4.3.0
│  └─ type-fest@^0.8.1
├─ ansi-regex@4.1.0
├─ ansi-styles@3.2.1
│  └─ color-convert@^1.9.0
├─ argparse@1.0.10
│  └─ sprintf-js@~1.0.2
├─ astral-regex@1.0.0
├─ balanced-match@1.0.0
├─ brace-expansion@1.1.11
│  ├─ balanced-match@^1.0.0
│  └─ concat-map@0.0.1
├─ callsites@3.1.0
├─ chalk@2.4.2
│  ├─ ansi-styles@^3.2.1
│  ├─ escape-string-regexp@^1.0.5
│  └─ supports-color@^5.3.0
├─ chardet@0.7.0
├─ cli-cursor@3.1.0
│  └─ restore-cursor@^3.1.0
├─ cli-width@2.2.0
├─ color-convert@1.9.3
│  └─ color-name@1.1.3
├─ color-name@1.1.3
├─ concat-map@0.0.1
├─ cross-spawn@6.0.5
│  ├─ nice-try@^1.0.4
│  ├─ path-key@^2.0.1
│  ├─ semver@^5.5.0
│  ├─ semver@5.7.1
│  ├─ shebang-command@^1.2.0
│  └─ which@^1.2.9
├─ debug@4.1.1
│  └─ ms@^2.1.1
├─ deep-is@0.1.3
├─ doctrine@3.0.0
│  └─ esutils@^2.0.2
├─ emoji-regex@7.0.3
├─ escape-string-regexp@1.0.5
├─ eslint-scope@5.0.0
│  ├─ esrecurse@^4.1.0
│  └─ estraverse@^4.1.1
├─ eslint-utils@1.4.3
│  └─ eslint-visitor-keys@^1.1.0
├─ eslint-visitor-keys@1.1.0
├─ eslint@6.8.0
│  ├─ @babel/code-frame@^7.0.0
│  ├─ ajv@^6.10.0
│  ├─ chalk@^2.1.0
│  ├─ cross-spawn@^6.0.5
│  ├─ debug@^4.0.1
│  ├─ doctrine@^3.0.0
│  ├─ eslint-scope@^5.0.0
│  ├─ eslint-utils@^1.4.3
│  ├─ eslint-visitor-keys@^1.1.0
│  ├─ espree@^6.1.2
│  ├─ esquery@^1.0.1
│  ├─ esutils@^2.0.2
│  ├─ file-entry-cache@^5.0.1
│  ├─ functional-red-black-tree@^1.0.1
│  ├─ glob-parent@^5.0.0
│  ├─ globals@^12.1.0
│  ├─ ignore@^4.0.6
│  ├─ import-fresh@^3.0.0
│  ├─ imurmurhash@^0.1.4
│  ├─ inquirer@^7.0.0
│  ├─ is-glob@^4.0.0
│  ├─ js-yaml@^3.13.1
│  ├─ json-stable-stringify-without-jsonify@^1.0.1
│  ├─ levn@^0.3.0
│  ├─ lodash@^4.17.14
│  ├─ minimatch@^3.0.4
│  ├─ mkdirp@^0.5.1
│  ├─ natural-compare@^1.4.0
│  ├─ optionator@^0.8.3
│  ├─ progress@^2.0.0
│  ├─ regexpp@^2.0.1
│  ├─ semver@^6.1.2
│  ├─ strip-ansi@^5.2.0
│  ├─ strip-json-comments@^3.0.1
│  ├─ table@^5.2.3
│  ├─ text-table@^0.2.0
│  └─ v8-compile-cache@^2.0.3
├─ espree@6.1.2
│  ├─ acorn-jsx@^5.1.0
│  ├─ acorn@^7.1.0
│  └─ eslint-visitor-keys@^1.1.0
├─ esprima@4.0.1
├─ esquery@1.0.1
│  └─ estraverse@^4.0.0
├─ esrecurse@4.2.1
│  └─ estraverse@^4.1.0
├─ estraverse@4.3.0
├─ esutils@2.0.3
├─ external-editor@3.1.0
│  ├─ chardet@^0.7.0
│  ├─ iconv-lite@^0.4.24
│  └─ tmp@^0.0.33
├─ fast-deep-equal@2.0.1
├─ fast-json-stable-stringify@2.1.0
├─ fast-levenshtein@2.0.6
├─ figures@3.1.0
│  └─ escape-string-regexp@^1.0.5
├─ file-entry-cache@5.0.1
│  └─ flat-cache@^2.0.1
├─ flat-cache@2.0.1
│  ├─ flatted@^2.0.0
│  ├─ rimraf@2.6.3
│  └─ write@1.0.3
├─ flatted@2.0.1
├─ fs.realpath@1.0.0
├─ functional-red-black-tree@1.0.1
├─ glob-parent@5.1.0
│  └─ is-glob@^4.0.1
├─ glob@7.1.6
│  ├─ fs.realpath@^1.0.0
│  ├─ inflight@^1.0.4
│  ├─ inherits@2
│  ├─ minimatch@^3.0.4
│  ├─ once@^1.3.0
│  └─ path-is-absolute@^1.0.0
├─ globals@12.3.0
│  └─ type-fest@^0.8.1
├─ has-flag@3.0.0
├─ iconv-lite@0.4.24
│  └─ safer-buffer@>= 2.1.2 < 3
├─ ignore@4.0.6
├─ import-fresh@3.2.1
│  ├─ parent-module@^1.0.0
│  └─ resolve-from@^4.0.0
├─ imurmurhash@0.1.4
├─ inflight@1.0.6
│  ├─ once@^1.3.0
│  └─ wrappy@1
├─ inherits@2.0.4
├─ inquirer@7.0.3
│  ├─ ansi-escapes@^4.2.1
│  ├─ ansi-regex@5.0.0
│  ├─ chalk@^2.4.2
│  ├─ cli-cursor@^3.1.0
│  ├─ cli-width@^2.0.0
│  ├─ emoji-regex@8.0.0
│  ├─ external-editor@^3.0.3
│  ├─ figures@^3.0.0
│  ├─ is-fullwidth-code-point@3.0.0
│  ├─ lodash@^4.17.15
│  ├─ mute-stream@0.0.8
│  ├─ run-async@^2.2.0
│  ├─ rxjs@^6.5.3
│  ├─ string-width@^4.1.0
│  ├─ string-width@4.2.0
│  │  ├─ emoji-regex@^8.0.0
│  │  ├─ is-fullwidth-code-point@^3.0.0
│  │  ├─ strip-ansi@^6.0.0
│  │  └─ strip-ansi@6.0.0
│  │     └─ ansi-regex@^5.0.0
│  ├─ strip-ansi@^5.1.0
│  └─ through@^2.3.6
├─ is-extglob@2.1.1
├─ is-fullwidth-code-point@2.0.0
├─ is-glob@4.0.1
│  └─ is-extglob@^2.1.1
├─ is-promise@2.1.0
├─ isexe@2.0.0
├─ js-tokens@4.0.0
├─ js-yaml@3.13.1
│  ├─ argparse@^1.0.7
│  └─ esprima@^4.0.0
├─ json-schema-traverse@0.4.1
├─ json-stable-stringify-without-jsonify@1.0.1
├─ levn@0.3.0
│  ├─ prelude-ls@~1.1.2
│  └─ type-check@~0.3.2
├─ lodash@4.17.15
├─ mimic-fn@2.1.0
├─ minimatch@3.0.4
│  └─ brace-expansion@^1.1.7
├─ minimist@0.0.8
├─ mkdirp@0.5.1
│  └─ minimist@0.0.8
├─ ms@2.1.2
├─ mute-stream@0.0.8
├─ natural-compare@1.4.0
├─ nice-try@1.0.5
├─ once@1.4.0
│  └─ wrappy@1
├─ onetime@5.1.0
│  └─ mimic-fn@^2.1.0
├─ optionator@0.8.3
│  ├─ deep-is@~0.1.3
│  ├─ fast-levenshtein@~2.0.6
│  ├─ levn@~0.3.0
│  ├─ prelude-ls@~1.1.2
│  ├─ type-check@~0.3.2
│  └─ word-wrap@~1.2.3
├─ os-tmpdir@1.0.2
├─ parent-module@1.0.1
│  └─ callsites@^3.0.0
├─ path-is-absolute@1.0.1
├─ path-key@2.0.1
├─ prelude-ls@1.1.2
├─ progress@2.0.3
├─ punycode@2.1.1
├─ regexpp@2.0.1
├─ resolve-from@4.0.0
├─ restore-cursor@3.1.0
│  ├─ onetime@^5.1.0
│  └─ signal-exit@^3.0.2
├─ rimraf@2.6.3
│  └─ glob@^7.1.3
├─ run-async@2.3.0
│  └─ is-promise@^2.1.0
├─ rxjs@6.5.4
│  └─ tslib@^1.9.0
├─ safer-buffer@2.1.2
├─ semver@6.3.0
├─ shebang-command@1.2.0
│  └─ shebang-regex@^1.0.0
├─ shebang-regex@1.0.0
├─ signal-exit@3.0.2
├─ slice-ansi@2.1.0
│  ├─ ansi-styles@^3.2.0
│  ├─ astral-regex@^1.0.0
│  └─ is-fullwidth-code-point@^2.0.0
├─ sprintf-js@1.0.3
├─ string-width@3.1.0
│  ├─ emoji-regex@^7.0.1
│  ├─ is-fullwidth-code-point@^2.0.0
│  └─ strip-ansi@^5.1.0
├─ strip-ansi@5.2.0
│  └─ ansi-regex@^4.1.0
├─ strip-json-comments@3.0.1
├─ supports-color@5.5.0
│  └─ has-flag@^3.0.0
├─ table@5.4.6
│  ├─ ajv@^6.10.2
│  ├─ lodash@^4.17.14
│  ├─ slice-ansi@^2.1.0
│  └─ string-width@^3.0.0
├─ text-table@0.2.0
├─ through@2.3.8
├─ tmp@0.0.33
│  └─ os-tmpdir@~1.0.2
├─ tslib@1.10.0
├─ tsutils@3.17.1
│  └─ tslib@^1.8.1
├─ type-check@0.3.2
│  └─ prelude-ls@~1.1.2
├─ type-fest@0.8.1
├─ typescript@3.7.4
├─ uri-js@4.2.2
│  └─ punycode@^2.1.0
├─ v8-compile-cache@2.1.0
├─ which@1.3.1
│  └─ isexe@^2.0.0
├─ word-wrap@1.2.3
├─ wrappy@1.0.2
└─ write@1.0.3
   └─ mkdirp@^0.5.1

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.

Содержание

  1. eslint errors on ‘interface’ keyword even when using this parser #620
  2. Comments
  3. Footer
  4. Parsing error: The keyword ‘export’ is reserved #1464
  5. Comments
  6. Ошибка синтаксического анализа: ключевое слово «импорт» зарезервировано.
  7. Код Visual Studio? – Другие текстовые редакторы или IDE?
  8. Предыдущие отчеты об ошибке
  9. использованная литература
  10. использованная литература
  11. 0. Предпосылки
  12. 1. Локально установите ESLint
  13. 2. Создайте .eslintrc.json файл, который работает
  14. Обновите все npm пакеты до последних версий
  15. Заключение
  16. использованная литература
  17. [eslint] Parsing error: The keyword ‘import’ is reserved #666
  18. Comments
  19. Footer

eslint errors on ‘interface’ keyword even when using this parser #620

I have Babel, ESLint, and Flow all being used in my React Native project. My .eslintrc looks like this:

For some reason, I’m getting an error when I try to declare an interface type in my code:

Not sure why. Could I have setup something wrong?

The text was updated successfully, but these errors were encountered:

Hi @jamesqo, Did you find any solution for this issue?
I got a similar error message.

Eslint version: v5.4.0

@AntonioTsai @jamesqo Did you find out?

I think this is expected behavior. It doesn’t look like Flow supports default exports of types or interfaces. See the bottom of this page for more details.

You can still export the interface, it just has to be named.

It is a reserved keyword, but one who uses Typescript. What’s the solution esp. when eslint runs on pre-commit.

From the documentation linked above it looks like export default interface <> isn’t valid Flow syntax, and so can’t be used with Flow. You’re correct that it is valid in TypeScript though (see microsoft/TypeScript@5ef6192).

I believe the easiest workaround would be to export the interface as a named export.

Thank you for the issue. Now that @babel/eslint-parser has been released, we are making this repository read-only. If this is a change you would still like to advocate for, please reopen this in the babel/babel monorepo.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Parsing error: The keyword ‘export’ is reserved #1464

What code were you trying to parse?

I’m trying to use typescript-eslint , and I followed the Getting Started page. Unfortunately, I’m having problems to make the parser identify very basic TypeScript/JS keywords, like export .

Please see https://github.com/flisboac/ts-promise-scheduler for the project in question. The error is:

My .eslint.js is configured as such:

And here are the first lines of the affected file

What did you expect to happen?

To accept export as a keyword, as per named/default export in TypeScript and the ES6+ standards, in the context of exporting declarations.

What actually happened?

export seems to be identified as a reserved name, regardless of context. Parsing fails.

Versions

Disclaimer:I’m using yarn .

package version
@typescript-eslint/parser 2.16.0
TypeScript 3.7.4
ESLint 6.8.0
node 12.13.0
npm 6.12.0
yarn 1.21.1

Output of yarn versions`:

Output of yarn list :

The text was updated successfully, but these errors were encountered:

Источник

Ошибка синтаксического анализа: ключевое слово «импорт» зарезервировано.

В коде Visual Studio я получаю Parsing error: The keyword ‘import’ is reserved . 1

Какие действия вы бы порекомендовали для исправления этой ошибки?

Я предоставляю свои .eslintrc.json и package.json файлы ниже.
Однако их, скорее всего, будет недостаточно для воспроизведения ошибки.
Итак, вот ссылка на zip-файл, содержащий все необходимые файлы проекта . 2

Проект (локально) устанавливается путем запуска npm install — это может занять около 5-9 минут.
Затем npm start следует открыть проект в веб-браузере по умолчанию. 3

Когда я делаю это и нажимаю F12 , я не получаю никаких ошибок, кроме двух предупреждений в консоли браузера.
Предупреждения:

‘unUsedArgument’ is defined but never used. Allowed unused args must match /^_/u no-unused-vars , а также

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

Ошибка в заголовке Parsing error: The keyword ‘import’ is reserved появляется, когда я открываю App.js в VS Code.

Но эта ошибка никак не связана с моим выбором текстового редактора,
в чем легко убедиться, запустив ESLint из командной строки.
Используйте первую строку, если вы используете Microsoft Windows (обратная косая черта).
Используйте вторую строку, если вы используете любую другую операционную систему (косая черта).

Код Visual Studio? – Другие текстовые редакторы или IDE?

Хотя я использую Visual Studio Code, я также приглашаю к ответам (и обсуждениям) других текстовых редакторов и IDE. Обратите внимание, что — помимо правильной установки ESLint через npm — вам также необходимо установить плагин/расширение для вашей конкретной интегрированной среды разработки (IDE).
В моем случае я использую это расширение VS Code ESLint . 4

Тем не менее, основное внимание здесь должно быть уделено npm команде и установленным пакетам Node.js.

Предыдущие отчеты об ошибке

В ссылках 5-12 из списка ниже я ссылаюсь на некоторые предыдущие отчеты об этой ошибке или подобных ошибках.
Некоторые из этих ссылок (вопросов) явно связаны с проблемой здесь, но, возможно, не все из них.

использованная литература

1 Слово import может быть const — или почти любое другое ключевое слово JavaScript.

2 Поскольку рекомендуется устанавливать ESLint локально , я предполагаю, что все читатели здесь так и делают.

3 В моем случае Google Chrome версии 98.0.4758.102, 64-бит. Запуск на Windows 10.

4 Помимо установки расширения, я добавил «eslint.nodePath»: «C:\Program Files\nodejs», его в свой (пользовательский) settings.json файл в VS Code. Никаких других изменений.

Вот простое решение — просто переместите rules атрибут from .eslintrc.json в eslintConfig атрибут package.json . 1

И не держи .eslintrc.json . Просто удалите его! 2

Теперь package.json файл будет следующим.

Убедитесь, что вы добились успеха.
Используйте первую строку, если вы используете Microsoft Windows (обратная косая черта).
Используйте вторую строку, если вы используете Linux или macOS (косая черта).

Если ваш текстовый редактор (в моем случае VS Code) все еще открыт, убедитесь, что вы перезапустили его, прежде чем вы ожидаете, что ошибка исчезнет!

использованная литература

1 Я получил идею из этого поста .

2 Не беги npm init @eslint/config .
Ошибки останутся, если вы не удалите .eslintrc.json !

3 A. Если вы подозреваете, что у вас может быть глобальная установка ESLint, сначала запустите:
npm uninstall eslint —global

Б. Если вы уже запустили npm install — как указано в строке 6 вопроса — вам не нужно запускать npm install eslint —save-dev для установки ESLint.
Потому что первый npm install также устанавливает ESLint , как я обнаружил при написании этого ответа .

0. Предпосылки

Если сервер запущен, закройте его, нажав Ctrl + C .

Я настоятельно рекомендую удалить все глобальные установки ESLint.
Чтобы увидеть, какие глобальные пакеты установлены, в командной строке выполните: 1

Если ESLint установлен глобально, удалите его, запустив:

Чтобы правильно установить ESLint в ваш локальный проект, я рекомендую выполнить следующие два шага.

Локально установите ESLint.

Создайте работающий .eslintrc.json файл.

Как оказалось, вам также нужно будет сделать третий шаг.

  1. Обновите все npm пакеты до последних версий.

1. Локально установите ESLint

Чтобы локально установить ESLint, запустите: 2

в конце package.json .

2. Создайте .eslintrc.json файл, который работает

ПРИМЕЧАНИЕ! Прежде чем двигаться дальше, сделайте себе одолжение, сохранив копию текущего .eslintrc.json файла, так как следующая команда уничтожит (воссоздаст) этот файл.

Чтобы создать новый .eslintrc.json файл, запустите:

Вам будет задан ряд вопросов, на которые я отвечу, нажав Enter для выбора значения по умолчанию, кроме формата , который я выбираю JSON (вместо JavaScript ).

В дополнение к созданию .eslintrc.json файла это также добавит «eslint-plugin-react»: «^7.29.2» атрибут devDependencies в package.json файл. 3

Команда npm init @eslint/config уничтожает существующий .eslintrc.json файл, поэтому вам придется вручную добавить обратно любые «rules» или другие параметры JSON, которые вы хотите сохранить.
В этом случае я добавляю обратно те правила, которые были в исходном файле .eslintrc.json .
Результат такой, как показано ниже.

Теперь, когда я открываю VS Code, вместо ошибки появляются два предупреждения, что и является желаемым результатом.

Здорово! Но подождите — к сожалению, оказывается, есть ложка дегтя. Проблема в том, что когда я запускаю npm start проект в веб-браузере и нажимаю F12 , в консоли появляются две ошибки.
Сообщения об ошибках:

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

К счастью, я уже выкладывал решение этой проблемы, а именно:
Обновите все npm пакеты до их последних версий .
Раздел ниже немного краток, поэтому, если вы хотите больше плоти на костях, посетите этот другой ответ .

Обновите все npm пакеты до последних версий

Рассмотрите возможность обновления всех npm пакетов до их последних версий.
Цель состоит в том, чтобы уменьшить риск возникновения конфликтов версий. В этом ответе также содержится
совет обновить все пакеты .

A. Глобальная установка npm-check-updates

В командной строке запустите:

B. Обновление package.json , чтобы содержать последние версии

Следующая команда запишет последние номера версий пакетов в ваш файл package.json :

Вот как это выглядит в Windows 10:

C. Установите последние версии

В командной строке запустите:

D. Проверьте наличие ошибок в браузере и/или в терминале

В командной строке запустите:

И браузер, и терминал теперь отображают пять ошибок .

Дискомфортно, а?

Определенно да! – Но не теряй надежды! Просто закройте сервер ( Ctrl + C ) и пробуйте снова и снова.
Вчера, когда я получил эти ошибки, все, что мне нужно было сделать, это запустить npm start еще раз.
Сегодня пробовал запускать npm start еще 4-5 раз, но все равно получаю ошибки.
Поэтому я попробовал npm install && npm start дважды, и, наконец, он заработал без ошибок.
Не уверен что происходит. Может быть, должно пройти какое-то время, прежде чем это сработает?

Наконец -то в браузере нет ошибок .

И терминал говорит, что скомпилировано успешно!

Заключение

Выполнение описанных выше шагов помогло мне исправить ошибку в заголовке вопроса:
Ошибка синтаксического анализа: ключевое слово «импорт» зарезервировано .

Для проекта с настройками даже немного другими, 5 просто копипаст из .eslintrc.json файла выше вряд ли сработает.
Запуск npm init @eslint/config и обновление всех пакетов с большей вероятностью будет успешным.

использованная литература

1 У меня Windows 10, но я ожидаю, что все приведенные здесь команды будут одинаково хорошо работать как в Linux, так и в macOS.

2 A. Выполнение этой команды займет около 5-10 минут.
Б. Пока ваш исходный код не преобразован Babel, нет необходимости устанавливать @babel/eslint-parser . Обычного eslint должно быть достаточно. См. Когда следует использовать @babel/eslint-parser ?
Если вы используете TypeScript, вам понадобится @babel/eslint-parser .
Команда для установки:
npm install eslint @babel/core @babel/eslint-parser —save-dev
Команда npm init @eslint/config конфигурации должна использоваться так же, как и для обычного ( не [email protected] ) ESLint.

3 Атрибут «eslint-plugin-react» in package.json , похоже, не имеет большого значения.

4 Оба предупреждения по-прежнему отображаются в текстовом редакторе, как и должны.

5 Например, вы можете использовать Angular или Vue вместо React.

Источник

[eslint] Parsing error: The keyword ‘import’ is reserved #666

I’m getting this error on the first import statement of any js file on grommet@0.6.6 (since 0.6.7 is having issues with npm install )

The text was updated successfully, but these errors were encountered:

what is your node and npm version? es6 is enabled via babel that should be installed in both 0.6.6 and 0.6.7.

Was there any issues in the console when you ran npm install ? Also, which environment are you in? Windows, Linux?

I was able to reproduce your issue.

For some weird reason the .babelrc is not present in the init command anymore. This will be fixed in the upcoming 0.6.8.

In the meantime, can you create in the root of your project a .babelrc file with the following content?

That file is already present in my project. Using grommet@0.6.6 I ran grommet init sample-app and without changing any files, I get the error above. I’m using node v6.2.2, npm 3.9.5 on OS X 10.11.5. I’m using a local copy of eslint (not installed globally). I’m running Visual Studio Code 1.2.1 using the ESLint extension.

Thanks for the detailed explaination. Are you able to run gulp dist ? In other words do you get the same issue in the command line?

Also can you try to validate the suggestion in this issue

I was able to run gulp dist without any issues.

I’ve found that adding .eslintrc.json to the root directory solves the problem.

Adding the same rules into customEslintrc.json does not seem to have any effect.

The weird thing is that in the commad line works. It feels to me this is an IDE specific issue.

Well, thanks for helping me through this regardless. I’m not sure why it doesn’t work by default, but having the .eslintrc.json there works.

cool. closing the issue. welcome to grommet. we invite you to join our slack channel for live support.

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

#javascript #reactjs #typescript #eslint

Вопрос:

Я пытаюсь запустить ESLint в своем проекте React только для того, чтобы проверить одно конкретное (например, max-len) правило, подобное этому:

 eslint . --ext .js,.jsx,.ts,.tsx --rule "{'max-len': ['error', { code: 120, ignoreComments: true, ignoreTrailingComments: true, ignoreUrls: true, ignoreStrings: true, ignoreTemplateLiterals: true, }]}"
 

Но результаты также показывают ошибки для других типов ошибок.

Вот мой .eslintrc.js файл:

 module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'react-app',
    'airbnb',
    'plugin:react/recommended',
    'plugin:import/errors',
    'plugin:import/warnings',
    'plugin:import/typescript',
    'plugin:jsx-a11y/recommended',
  ],
  plugins: [
    'react',
    'jsx-a11y',
    '@typescript-eslint',
  ],
  // parser: 'babel-eslint',
  parserOptions: {
    ecmaFeatures: {
      jsx: true,
    },
    ecmaVersion: 2017,
    sourceType: 'module',
  },
  settings: {
    'import/resolver': {
      node: {
        extensions: ['.js', '.jsx', '.ts', '.tsx'],
      },
    },
  },
  rules: {
    'max-len': ['error', {
      code: 120,
      ignoreComments: true,
      ignoreTrailingComments: true,
      ignoreUrls: true,
      ignoreStrings: true,
      ignoreTemplateLiterals: true,
    }],
  },
};
 

Я также пытался запустить с игнорированием файла .eslintrc.js используя --no-eslintrc вот так:

 eslint . --ext .js,.jsx,.ts,.tsx --no-eslintrc --rule ....same-rule-above
 

На этот раз я получаю только одну ошибку max-len, а остальные-ошибки при анализе ключевого слова импорта:

 /Users/olcayertas/10n/src/util/helpers.ts
  1:1  error  Parsing error: The keyword 'import' is reserved

/Users/olcayertas/10n/src/util/routes.ts
  1:1  error  Parsing error: The keyword 'export' is reserved

/Users/olcayertas/10n/src/util/ui-helpers.ts
  1:1  error  Parsing error: The keyword 'import' is reserved

✖ 196 problems (196 errors, 0 warnings)
 

Как я могу запустить ESLint только для одного правила с объектом правила?

Комментарии:

1. Видеть eslint.org/docs/user-guide/command-line-interface#-rule

2. Что вы подразумеваете под «exp» (в первом предложении)?

Ответ №1:

Я нахожу проблему, и вот ответ. Поскольку наш проект использует TypeScript, нам нужна конфигурация eslintrc.js файла, поэтому использование --no-eslintrc не работает. Вместо этого мы отключили расширенные правила (а не плагины).:

 module.exports = {
  ...
  extends: [
    'plugin:import/errors',
    'plugin:import/warnings',
    'plugin:import/typescript',
    //'plugin:react/recommended',
    //'arbnb',
  ],
  rules: {
    'react/jsx-filename-extension': [1, { extensions: ['.js', '.jsx', '.ts', '.tsx'] }],
    'import/prefer-default-export': 'off',
    'import/no-unresolved': ['error', { ignore: [ '.svg' ] } ],
    'import/extensions': [
      'error',
      'ignorePackages',
      {
        js: 'never',
        jsx: 'never',
        ts: 'never',
        tsx: 'never',
      },
    ],
  },
}
 

Поскольку я хочу видеть ошибки при импорте, я оставил плагины и правила включенными для импорта. После отключения расширенных правил я запускаю эту команду:

 eslint . --ext .js,.jsx,.ts,.tsx
 

И это работает идеально! Таким образом, мы можем добавлять правила шаг за шагом.

Комментарии:

1. Вероятно, проще создать «базовый» набор правил, который вы можете использовать для компоновки из командной строки, и ваш фактический файл конфигурации ESLint просто расширит базовый и другие предустановки.

Ответ №2:

Если вы хотите использовать файл .eslintrc для сохранения своей конфигурации (парсер, настройки плагина и т. Д.), Вы можете использовать eslint-nibble с --rule=max-len флагом. Это будет соответствовать вашей обычной конфигурации, но покажет вам только ошибки из этого правила и даст возможность исправить их, если правило можно исправить автоматически.

Отказ от ответственности: Я создатель eslint-nibble.

У меня проблема с eslint, это дает мне [Parsing Error. Импорт ключевых слов — это резерв], это происходит только в возвышенном виде, в редакторе атомов хорошо работает. У меня есть eslint

.eslintrc.js

module.exports = {
    "extends": "airbnb",
    "plugins": [
        "react"
    ]
};

package.json

{
  "name": "paint",
  "version": "0.0.0",
  "description": "paint on the browser",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [
    "paint",
    "javascript"
  ],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "browserify": "^11.2.0",
    "eslint": "^2.2.0",
    "eslint-config-airbnb": "^2.1.1",
    "eslint-plugin-react": "^3.11.2",
    "gulp-babel": "^5.2.1",
    "gulp-clean": "^0.3.1",
    "gulp-stylus": "^2.2.0",
    "vinyl-source-stream": "^1.1.0"
  }
}

Ответ 1

Проблема заключалась в том, что я установил eslint глобально и локально, вызывая несогласованности в SublimeLinter-contrib-eslint. Я удалил eslint глобально, и SublimeLinter работает.

Ответ 2

Добавьте это в корень вашего .eslintrc

"parser": "babel-eslint"

и обязательно запустите:

npm i babel-eslint --save-dev

Ответ 3

Опция eslint, которая решает ошибку «Импорт ключевого слова зарезервирован» — это parserOptions.sourceType. Установка его в "module" позволяет использовать ключевое слово import.

.eslintrc

{
    "parserOptions": {
        "sourceType": "module"
    }
}

Документы: https://eslint.org/docs/user-guide/configuring#specifying-parser-options

Ответ 4

Не уверен, но попробуйте переименовать файл в .eslintrc и просто используйте

{
  "extends": "airbnb",
  "plugins": ["react"]
};

Также убедитесь, что у вас установлены необходимые пакеты.
github.com/airbnb/javascript

Ответ 5

Я также получил эту ошибку в проекте meteor, и я смог решить, что установка sourceType в «module»
более подробную информацию можно найти в документах Eslint:
http://eslint.org/docs/user-guide/configuring#specifying-parser-options

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.

Running 'npm start' gives 2 warnings in the browser but no error

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.

npx eslint src

Parsing error: The keyword 'import' is reserved

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.

Parsing error: The keyword 'import' is reserved

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

package.json :

{
  "name": "parsing-error",
  "version": "0.1.0",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.1",
    "@testing-library/user-event": "^7.2.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version"
    ]
  }
}

.eslintrc.json :

{
  "rules": {
    "no-unused-vars": [
      "warn",
      {
        "argsIgnorePattern": "^_",
        "varsIgnorePattern": "^_"
      }
    ]
  }
}

4. Is this question a duplicate?

I have been asked : is my question here a duplicate of
Parsing Error The Keyword import is Reserved
(SublimeLinter-contrib-eslint)?

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-name-of-my-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 the Community FAQ index for Stack Overflow there is a link to
what I can do when I think my question is not a duplicate, which in turn links to
another post that (implicitly) defines when a question is a
duplicate of another 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.

The babel-eslint package has been deprecated.

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

  • What does MCVE mean – minimal, complete and verifiable example?
  • Zip file containing the needed project files
  • To install ESLint globally rather than locally (using
    npm install eslint --global) is not recommended
  • VS Code ESLint extension
  • In VS Code, add "eslint.nodePath": "C:\Program Files\nodejs",
    to settings.json
  • Parsing Error The Keyword import is Reserved
    (SublimeLinter-contrib-eslint)
  • Create React App
  • The react-scripts npm package
  • How is ESLint integrated into Create React App?
  • eslint-config-react-app
  • @babel/eslint-parser
  • The Community FAQ index for Stack Overflow
  • What can I do when I think my question’s not a duplicate?
  • A post that (implicitly) defines when a question is a duplicate of
    another question
  • The highest voted answer of other question
  • The deprecated babel-eslint package
  • Installing ESLint globally might be a bad idea
  • Parsing error: The keyword ‘export’ is reserved
  • Parsing error: The keyword ‘import’ is reserved
  • ERROR: Parsing Error: The keyword ‘const’ is reserved
  • eslint: error Parsing error: The keyword ‘const’ is reserved
  • Setting up Airbnb ESLint with React and Webpack
  • Parsing error: The keyword ‘enum’ is reserved
  • ESLint Parsing error: Unexpected token

1
Since it is recommended to install ESLint locally,
I assume all readers here do so.

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.

package.json :

{
  "name": "parsing-error",
  "version": "0.1.0",
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.4.1",
    "@testing-library/user-event": "^7.2.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "4.0.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app",
    "rules": {
      "no-unused-vars": [
        "warn",
        {
          "argsIgnorePattern": "^_",
          "varsIgnorePattern": "^_"
        }
      ]
    }
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version"
    ]
  }
}

That’s it!
3

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).

node_modules.bineslint . --ext .js
node_modules/.bin/eslint . --ext .js

Expect to see:

With adequate rules under eslintConfig in package.json, both unused identifiers are warned about

No error. – Yay!

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

  • Another solution to Parsing error: The keyword 'import' is reserved
  • Suggesting to have ESLint rules in package.json under
    eslintConfig
  • Installation of ESLint using npm
  • ESLint may get installed even if not explicitly mentioned in
    package.json

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

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.

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.

Понравилась статья? Поделить с друзьями:
  • Eslint parsing error import and export may appear only with sourcetype module
  • Eslint optional chaining parsing error unexpected token
  • Eslint npm error
  • Esl4550ro ошибка i20
  • Esia1 код ошибки