简体   繁体   English

“解析错误:保留关键字'import'”

[英]"Parsing error: The keyword 'import' is reserved"

In Visual Studio Code I get Parsing error: The keyword 'import' is reserved .在 Visual Studio Code 我得到Parsing error: The keyword 'import' is reserved

What actions would fix this error?哪些操作可以修复此错误?

0. A minimal, complete and verifiable example 0. 一个最小的、完整的和可验证的例子

I provide my .eslintrc.json and package.json files in Section 2 below.我在下面的第 2 节中提供了我的.eslintrc.jsonpackage.json文件。
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 .所以这里是一个包含所有必要项目文件的 zip 文件的链接。

To locally install the project, run npm install .要在本地安装项目,请运行npm install – This may take about 5-9 minutes. – 这可能需要大约 5-9 分钟。 1 1
Then npm start should open the project in the default web browser.然后npm start应该在默认的 Web 浏览器中打开项目。 2 2

When I do this and hit F12 , I get no errors but two warnings in the console of the browser.当我这样做并点击F12时,我没有收到任何错误,但在浏览器的控制台中有两个警告。

The warnings are in line with the rules in .eslintrc.json (Section 2 below) :警告符合.eslintrc.json中的规则(下面的第 2 节):

  • 'unUsedArgument' is defined but never used. Allowed unused args must match /^_/u no-unused-vars 'unUsedArgument' is defined but never used. Allowed unused args must match /^_/u no-unused-vars , and '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 'unUsedVariable' is assigned a value but never used. Allowed unused vars must match /^_/u no-unused-vars . '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 1.解析错误:关键字'import'被保留

The error in the title has nothing to do with my choice of text editor.标题中的错误与我选择的文本编辑器无关。
This is easily confirmed by running ESLint from the command line.这很容易通过从命令行运行 ESLint 来确认。

npx eslint src

Parsing error: The keyword 'import' is reserved

2. Configuration files of my reproducible example 2.我的可重现示例的配置文件

package.json : 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 : .eslintrc.json

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

3. Visual Studio Code? 3.Visual Studio 代码? – Other text editors or IDE:s? – 其他文本编辑器或 IDE:s?

The error, Parsing error: The keyword 'import' is reserved , also shows up when I open App.js in VS Code.当我在 VS Code 中打开App.js时,也会出现错误Parsing error: The keyword 'import' is reserved

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.虽然我使用的是 Visual Studio Code,但我也邀请其他文本编辑器和 IDE:s 的回答(和讨论)。 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).请注意 - 除了通过npm正确安装 ESLint - 您还必须为您的特定集成开发环境 (IDE) 安装插件/扩展。
In my case, I use the official VS Code ESLint extension .就我而言,我使用官方的 VS Code ESLint extension 3 3

Still, the focus here should clearly be on what npm packages have been installed.尽管如此,这里的重点显然应该放在安装了哪些npm包上。

4. Is this question a duplicate? 4. 这个问题是重复的吗?

I have been asked : is my question here a duplicate of有人问我:我的问题是不是重复的
Parsing Error The Keyword import is Reserved (SublimeLinter-contrib-eslint) ?解析错误关键字导入被保留(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我的问题的package.json的起源来自通过命令创建 React App
npx create-react-app <the-name-of-my-app> . 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.另一个问题的package.json缺少每个 Create React App必须具有的react-scripts npm 包。 The other question is clearly not about Create React App , whereas my question is .另一个问题显然与Create React App无关,而我的问题 4 4

4a. 4a。 How is ESLint integrated into Create React App? ESLint 如何集成到 Create React App 中?

As this answer explains, a Create React App depends directly on the react-scripts package.正如这个答案所解释的,一个Create React App直接依赖于react-scripts包。

The react-scripts package in turn depends on the eslint-config-react-app package (and on many other packages), which in turn depends on the @babel/eslint-parser package. react-scripts包又依赖于eslint-config-react-app包(以及许多其他包),而后者又依赖于@babel/eslint-parser包。 I will come back to the latter dependency in the next subsection.我将在下一小节中回到后一种依赖关系。

4b. 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 .Stack Overflow 的社区常见问题解答索引中,有一个链接指向当我认为我的问题不是重复问题时我可以做什么,该链接又链接到另一个帖子,该帖子(隐式)定义问题何时与另一个问题重复

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 .首先,投票最高的答案已经过时,因为它建议安装已弃用的babel-eslint The authors of that package explicitly instruct to use the successor package @babel/eslint-parser instead of babel-eslint .该包的作者明确指示使用后继包@babel/eslint-parser而不是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 (via eslint-config-react-app ).在我的Create React App示例中,安装已弃用的babel-eslint包会更加成问题,因为@babel/eslint-parser已经安装(通过eslint-config-react-app )。 I cannot accept a proposed solution that simultaneously installs two different versions of the ESLint Parser (of which one is deprecated).我不能接受同时安装两个不同版本的ESLint 解析器(其中一个已被弃用)的建议解决方案。 So the highest voted answer is not an acceptable answer to the the question I ask here.因此,对于我在这里提出的问题,最高投票的答案不是可接受的答案。

The accepted answer is not relevant in my case, as I installed ESLint only locally (not globally).接受的答案与我的情况无关,因为我仅在本地(而不是全局)安装了 ESLint。

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.他们中的大多数导致了与我不同的错误消息,但没有一个解决了我的问题——与我在下面发布的两个自我答案相反。

4c. 4c。 Concluding remarks结束语

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) .我得出结论,我的问题不是Parsing Error The Keyword import is Reserved (SublimeLinter-contrib-eslint) 的重复

5. Other reports of the error 5.其他报错

References 18-24 of the list below are links to previous reports of the error – or similar errors.下面列表中的参考 18-24 是指向先前错误报告或类似错误的链接。
Some of those links (questions) are likely related to the issue here, but possibly not all of them.其中一些链接(问题)可能与这里的问题有关,但可能不是全部。

References参考


1 Since it is recommended to install ESLint locally , I assume all readers here do so. 1由于推荐在本地安装 ESLint ,我假设这里的所有读者都这样做。

2 In my case Google Chrome Version 98.0.4758.102, 64-bit. 2在我的情况下,Google Chrome 版本 98.0.4758.102,64 位。 Running on Windows 10.在 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. 3除了安装扩展之外,我还在 VS Code 中的(用户) settings.json文件中添加了"eslint.nodePath": "C:\\Program Files\\nodejs", No other changes.没有其他变化。

4 I have added the tag to my question. 4我已将标签添加到我的问题中。

Here is a simple solution – just move the rules attribute from .eslintrc.json to the eslintConfig attribute of package.json .这是一个简单的解决方案——只需将rules属性从.eslintrc.json移动到package.jsoneslintConfig属性。 1 1

And don't keep .eslintrc.json .并且不要保留.eslintrc.json Just delete it!删除它! 2 2

The package.json file will now be as follows. package.json文件现在如下所示。

package.json : 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 3

Check to see that you were successful :检查您是否成功:

npx eslint . --ext .js

Expect to see :期待看到:

Using eslintConfig in package.json makes the error go away.

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!如果您的文本编辑器(在我的情况下为 VS Code)仍然打开,请确保在您期望看到错误消失之前重新启动它!

References参考


1 I got the idea from this post . 1我从这篇文章中得到了这个想法。

2 Don't run npm init @eslint/config either. 2也不要运行npm init @eslint/config The error(s) will persevere if you don't delete .eslintrc.json !如果您不删除.eslintrc.json ,错误将持续存在!

3 A. If you suspect that you may have a global installation of ESLint, first run: 3 A. 如果你怀疑你可能有 ESLint 的全局安装,首先运行:
npm uninstall eslint --global

B. If you have already run npm install – as suggested on line 7 of the question – then you shouldn't need to run npm install eslint --save-dev to install ESLint. B. 如果你已经运行npm install ——正如问题第 7 行所建议的那样——那么你不需要运行npm install eslint --save-dev来安装 ESLint。
The reason is that having react-scripts in package.json means that ESLint gets installed by npm install .原因是在package.json中有react-scripts意味着ESLint 是由npm install
Section 1 of this answer tells us that ESLint is in the dependency tree of react-scripts .这个答案的第 1 节告诉我们 ESLint 在react-scripts的依赖树中。

0. Prerequisites 0. 先决条件

If the server is running, close it by hitting Ctrl + C .如果服务器正在运行,请按Ctrl + C将其关闭。

I strongly recommend uninstalling any global installations of ESLint.我强烈建议卸载任何全局安装的 ESLint。
To see what global packages are installed, in the command line run: 1要查看安装了哪些全局包,请在命令行中运行: 1

npm list --global --depth 0

If ESLint is globally installed, uninstall by running:如果 ESLint 已全局安装,请运行以下命令卸载:

npm uninstall eslint --global

To correctly install ESLint into your local project, I recommend performing the following two steps.要将 ESLint 正确安装到本地项目中,我建议执行以下两个步骤。

  1. Locally install ESLint.本地安装 ESLint。

  2. Create a functioning .eslintrc.json file.创建一个正常运行的.eslintrc.json文件。

As it turns out, you will also need to do a third step.事实证明,您还需要执行第三步。

  1. Update all npm packages to their latest versions.将所有npm包更新到最新版本。

1. Locally install ESLint 1.本地安装ESLint

To locally install ESLint, run: 2要在本地安装 ESLint,请运行: 2

npm install eslint --save-dev

This will add这将添加

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

at the end of package.json .package.json的末尾。

2. Create a .eslintrc.json file that works 2. 创建一个有效的.eslintrc.json文件

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.在继续之前,请保存当前.eslintrc.json文件的副本,帮自己一个忙,因为下一个命令将销毁(重新创建)该文件。

To create a new .eslintrc.json file, run:要创建一个新的.eslintrc.json文件,请运行:

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 ).您将被问到一些问题,我通过按Enter选择默认值来回答这些问题,除了我选择JSON (而不是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.除了创建.eslintrc.json文件之外,这还会将 devDependencies 下的"eslint-plugin-react": "^7.29.2"属性devDependenciespackage.json文件中。 3 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.命令npm init @eslint/config会破坏现有的.eslintrc.json文件,因此您必须手动添加任何"rules"或您想要保留的其他 JSON 设置。
In this case, I add back the rules that were in the original .eslintrc.json .在这种情况下,我添加了原始.eslintrc.json中的规则。
The result is as below.结果如下。

.eslintrc.json : .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 时,没有出现错误,而是出现了两个警告,这正是预期的结果。

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.问题是,当我现在运行npm start在 Web 浏览器中打开项目并点击F12时,控制台中显示了两个错误。
The error messages are:错误消息是:

  • Uncaught ReferenceError: process is not defined , and Uncaught ReferenceError: process is not defined
  • Line 0: Parsing error: ImportDeclaration should appear when the mode is ES6 and in the module context . 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 .将所有npm包更新到最新版本
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将所有npm包更新到最新版本

Consider updating all npm packages to their latest versions.考虑将所有npm包更新到最新版本。
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 A. 全局安装npm-check-updates

In the command line, run:在命令行中,运行:

npm install --global npm-check-updates

B. Update package.json to contain the latest versions B. 更新package.json以包含最新版本

The following command will write the latest package version numbers to your package.json :以下命令会将最新的包版本号写入您的package.json

npm-check-updates --upgrade

Here is what it looks like in Windows 10:这是它在 Windows 10 中的样子:

Upgrading package.json

C. Install the latest versions C. 安装最新版本

In the command line, run:在命令行中,运行:

npm install

D. Check for errors in the browser and/or in the terminal D. 检查浏览器和/或终端中的错误

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.只需关闭服务器( Ctrl + C )并一遍又一遍地尝试。
Yesterday when I got these errors, all I needed to do was to run npm start one more time.昨天当我遇到这些错误时,我需要做的就是再运行一次npm start
Today I tried running npm start 4-5 more times, but still got the errors.今天我尝试再运行npm start 4-5 次,但仍然出现错误。
So I tried npm install && npm start twice, and finally it ran without errors.所以我尝试了两次npm install && npm start ,最后它运行没有错误。
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 4

Conclusion结论

Following the steps above helped me remedy the error in the question title:按照上述步骤帮助我纠正了问题标题中的错误:
Parsing error: The keyword 'import' is reserved .解析错误:关键字“import”被保留

For a project with settings even slightly different, 5 just copy-pasting from the .eslintrc.json file above is unlikely to work.对于设置稍有不同的项目,从上面的.eslintrc.json文件中复制粘贴5不太可能起作用。
Running npm init @eslint/config and upgrading all packages is more likely to be successful.运行npm init @eslint/config并升级所有包更有可能成功。

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. 1我使用的是 Windows 10,但我希望此处提供的所有命令在 Linux 和 macOS 上都能正常工作。

2 A. Expect this command to take about 5-10 minutes to complete. 2 A. 预计此命令大约需要 5-10 分钟才能完成。
B. As long as your source code is not transformed by Babel, there is no reason to install @babel/eslint-parser . B. 只要你的源代码没有被 Babel 转换,就没有理由安装@babel/eslint-parser Just normal eslint should be enough.只是普通eslint就足够了。 See When should I use @babel/eslint-parser ?请参阅何时应该使用@babel/eslint-parser
If you are using TypeScript, then you will need @babel/eslint-parser .如果您使用的是 TypeScript,那么您将需要@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 -@babel) ESLint. npm init @eslint/config配置命令应该以与普通(-@babel)ESLint 相同的方式使用。

3 The "eslint-plugin-react" attribute in package.json does not seem to be of much relevance though. 3 package.json中的"eslint-plugin-react"属性似乎没有太大的相关性。

4 The two warnings still show up in the text editor – just as they should. 4这两个警告仍然显示在文本编辑器中——就像它们应该出现的那样。

5 For example, you might be using Angular or Vue instead of React. 5例如,您可能正在使用 Angular 或 Vue 而不是 React。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM