简体   繁体   English

由于 ESLint 错误,我的 create-react-app 无法编译

[英]My create-react-app is failing to compile due to ESLint error

I just created a fresh template with create-react-app with react v17 included, and I installed eslint dependencies as I used to before, here's my package.json file我刚刚创建了一个包含react v17 的带有create-react-app的新模板,并且像以前一样安装了 eslint 依赖项,这是我的 package.json 文件

{
  "name": "gym-nation",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.11.5",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "axios": "^0.21.0",
    "classnames": "^2.2.6",
    "moment": "^2.29.1",
    "prop-types": "^15.7.2",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-helmet": "^6.1.0",
    "react-intl": "^5.8.6",
    "react-redux": "^7.2.1",
    "react-router": "^5.2.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.0",
    "redux": "^4.0.5",
    "redux-thunk": "^2.3.0",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^4.5.0",
    "@typescript-eslint/parser": "^4.5.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^7.12.0",
    "eslint-config-airbnb": "^18.2.0",
    "eslint-config-prettier": "^6.14.0",
    "eslint-config-react-app": "^6.0.0",
    "eslint-plugin-flowtype": "^5.2.0",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jest": "^24.1.0",
    "eslint-plugin-jsx-a11y": "^6.3.1",
    "eslint-plugin-prettier": "^3.1.4",
    "eslint-plugin-react": "^7.21.5",
    "eslint-plugin-react-hooks": "^4.2.0",
    "eslint-plugin-testing-library": "^3.9.2",
    "node-sass": "^4.14.1",
    "prettier": "^2.1.2",
    "react-app-rewired": "^2.1.6"
  }
}

and here's my eslintrc.json: (note that i didn't add all the rules yet)这是我的 eslintrc.json :(请注意,我还没有添加所有规则)

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": ["react-app", "prettier"],
  "parserOptions": {
    "ecmaFeatures": {
      "jsx": true
    },
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "plugins": ["react", "prettier"],
  "rules": {
    "prettier/prettier": [
      "error",
      {
        "printWidth": 140,
        "singleQuote": true,
        "editor.formatOnSave": true,
        "arrowParens": "always",
        "jsxSingleQuote": true,
        "tabWidth": 2,
        "trailingComma": "none"
      }
    ],
    "no-unused-vars": "error"
  }
}

when I run the app will fail to compile due to this error:当我运行应用程序时,由于此错误而无法编译:

Line 113:13:  'isLoading' is assigned a value but never used  no-unused-vars

I've worked on previous projects and eslint errors were showing in the code without causing the app to crash.我从事过以前的项目,并且代码中显示了 eslint 错误,而不会导致应用程序崩溃。 can anyone point where I messed up please?谁能指出我搞砸的地方?

I have had the exact same errors when I created app using the create-react-app and setup the eslint for the application.当我使用create-react-app应用程序并为应用程序设置 eslint时,我遇到了完全相同的错误。

The eslint errors were showing up in the browser rather than in the console . eslint 错误显示在浏览器而不是控制台中。

Once, I debugged all the dependencies.有一次,我调试了所有依赖项。 It seems that the react-scripts was causing the lint errors for me.似乎react-scripts对我造成了 lint 错误。

The newest version of the react-scripts:"4.0.0" may have some breaking changes which could be causing the eslint to throw the errors in the browser.最新版本的react-scripts:"4.0.0"可能有一些重大更改,可能导致 eslint 在浏览器中抛出错误。

Solution:解决方案:

This issue has been fixed in the react-scipts:"4.0.3" but, the eslint errors present in the project are not converted to warnings by default .此问题已在react-scipts:"4.0.3"中修复,但项目中存在的 eslint 错误默认不会转换为警告 You have to create an .env file which should contain a ESLINT_NO_DEV_ERRORS=true flag.您必须创建一个.env 文件,该文件应包含ESLINT_NO_DEV_ERRORS=true标志。 Due to this flag, you will receive the eslint errors as warnings and not as errors in the development .由于这个标志,您将收到eslint 错误作为警告不是开发中的错误

This flag is ignored during production and when they are any git hooks running, which will in turn cause an error when you are trying to commit the code with an eslint error in it .这个标志在生产过程中被忽略,当它们运行任何 git 钩子时,当你尝试提交带有eslint 错误的代码时,这反过来会导致错误

Update 2:更新 2:

Active Issue: https://github.com/facebook/create-react-app/issues/9887活动问题: https ://github.com/facebook/create-react-app/issues/9887

Workaround for this issue until react-scripts:4.0.2 is released:在 react-scripts:4.0.2 发布之前,此问题的解决方法:

  • Install patch-package and postinstall-postinstall as dev dependency .安装patch-packagepostinstall-postinstall作为 dev 依赖项。

  • Go to node_modules/react-scripts/config/webpack.config.js and make the following changes转到node_modules/react-scripts/config/webpack.config.js并进行以下更改变化

  • Once done with the edit,run yarn patch-package react-scripts .完成编辑后,运行yarn patch-package react-scripts This will create a patches folder , with the dependency patch in it.这将创建一个补丁文件夹,其中包含依赖补丁

  • Now, as we don't want do this every time while installing the dependencies.现在,因为我们不想在安装依赖项时每次都这样做 We are going to add another script to our package.json file.我们将在 package.json 文件中添加另一个脚本

    "postinstall":"patch-package" . "postinstall":"patch-package"

This above script will run every time when we install the dependencies.每次我们安装依赖项时,上面的脚本都会运行 Just keep in mind that you will also have to push packages folder to your repo.请记住,您还必须将包文件夹推送到您的存储库。 If you need the changes, also while deploying the app.如果您需要更改,也可以在部署应用程序时进行。

Thanks to @fernandaad for providing this workaround.感谢 @fernandaad 提供此解决方法。

Update 1:更新1:

Had to downgrade to react-scripts:3.4.4 version because there is no workaround available right now.不得不降级到react-scripts:3.4.4版本,因为目前没有可用的解决方法。 Now, errors were being thrown in the console rather than in the browser.现在,错误被抛出在控制台而不是浏览器中。

  1. Delete the node_modules and package.lock/yarn.lock.删除 node_modules 和 package.lock/yarn.lock。
  2. Downgrade react-scripts from 4.0.0 to 3.4.4.将 react-scripts 从 4.0.0 降级到 3.4.4。
  3. Install the dependencies and start the app.安装依赖项并启动应用程序。

I was able to fix it using env variables, since I'm not using webpack.我能够使用 env 变量修复它,因为我没有使用 webpack。

Make sure you're using the VSCode extension and that you installed eslint as a dev-dependency (as well as any other plugins you might need).确保您使用的是 VSCode 扩展,并且安装了 eslint 作为开发依赖项(以及您可能需要的任何其他插件)。

To get your code to lint, but not fail, in development, add this to your .env.development : ESLINT_NO_DEV_ERRORS=true要让您的代码在开发中进行 lint,但不会失败,请将其添加到您的.env.development 中ESLINT_NO_DEV_ERRORS=true

To completely disable eslint on a production build, add this to your .env.production : DISABLE_ESLINT_PLUGIN=true要在生产版本中完全禁用 eslint,请将其添加到您的.env.production 中DISABLE_ESLINT_PLUGIN=true

After that, it should not fail any build.之后,它不应失败任何构建。 I don't understand why eslint should fail builds.我不明白为什么 eslint 会失败构建。 It's there to help us keep code quality up, but not necessarily enforce it.它可以帮助我们保持代码质量,但不一定要强制执行。

it took me some hours to find possible solutions:我花了几个小时才找到可能的解决方案:

1- workaround: add rules inside the package.json file 1- 解决方法:在package.json文件中添加规则

  "eslintConfig": {
    "extends": ["react-app"],
    "rules": {
      "no-unused-vars": "warn"
    },
    "overrides": [
      {
        "files": ["**/*.ts?(x)"],
        "rules": {
          "max-len": "warn"
        }
      }
    ]
  },

2- you can use a .eslintrc.js file, by adding .env file in the root folder with following content: 2-您可以使用.eslintrc.js文件,方法是在根文件夹中添加具有以下内容的.env文件:

DISABLE_ESLINT_PLUGIN=true
ESLINT_NO_DEV_ERRORS=true
  • DISABLE_ESLINT_PLUGIN- will disable eslint-webpack-plugin in the Development and Production. DISABLE_ESLINT_PLUGIN- 将在开发和生产中禁用eslint-webpack-plugin - this is a must. - 这是必须的。

  • ESLINT_NO_DEV_ERRORS - will convert ESLint errors to warnings during development. ESLINT_NO_DEV_ERRORS - 在开发过程中将 ESLint 错误转换为警告。 As a result, ESLint output will no longer appear in the error overlay.因此,ESLint 输出将不再出现在错误覆盖中。 this alone won't fix the bug.仅此一项并不能修复错误。

see also documentation here and here另请参阅此处此处的文档

The genius developers arround react-scripts decided to turn warnings into errors once CI=true is present.围绕 react-scripts 的天才开发人员决定在CI=true出现后将警告变为错误。 Therefore the only way to fix that is using CI=false for your command or make your eslint run warning free.因此,解决此问题的唯一方法是对您的命令使用CI=false或让您的 eslint 运行无警告。 There is no point to suggest eslint rules here cause yet another warning caused by your codebase or custom ruleset might trigger that issue.没有必要在这里建议 eslint 规则会导致由您的代码库或自定义规则集引起的另一个警告可能会触发该问题。

Adjust your scripts block in package.json :调整package.json中的scripts块:

"scripts": {
  "start": "CI=false react-app-rewired start",
  "build": "CI=false react-app-rewired build",
  "test": "react-app-rewired test",
  "eject": "react-scripts eject"
}

Or run it that way:或者这样运行:

CI=false npm run start
CI=false npm run build

See related issues on GitHub:在 GitHub 上查看相关问题:

https://github.com/facebook/create-react-app/issues/10062 https://github.com/facebook/create-react-app/issues/10062

https://github.com/facebook/create-react-app/issues/9887 https://github.com/facebook/create-react-app/issues/9887

For Next.js对于Next.js

Open next.config.js and enable the ignoreDuringBuilds option in the eslint config:打开next.config.js并在 eslint 配置中启用ignoreDuringBuilds选项:

module.exports = {
  eslint: {
    ignoreDuringBuilds: true
  }
}

For a temporary workaround, use .eslintrc.js so that you can check your current node environment and set rules accordingly.对于临时解决方法,请使用.eslintrc.js以便您可以检查当前节点环境并相应地设置规则。 Eg:例如:

const isProd = process.env.NODE_ENV === 'production';
const warnDevErrorProd = isProd ? 2 : 1;

{
  ...
  "rules": {
    ...
    "prettier/prettier": warnDevErrorProd,
    "no-console": warnDevErrorProd,
    ...
  }
  ...
}

This way you don't need to eject in order to modify your webpack config to change the rules there.这样你就不需要弹出来修改你的 webpack 配置来改变那里的规则。

This Compiled with problems can also solved to add this in the .env file. This Compiled with questions 也可以通过在 .env 文件中添加这个来解决。 I face the problem and try to solve it using this line of code.我面临这个问题并尝试使用这行代码来解决它。

SKIP_PREFLIGHT_CHECK=true

or或者

ESLINT_NO_DEV_ERRORS=true

SKIP_PREFLIGHT_CHECK=true or ESLINT_NO_DEV_ERRORS=true

or you can also edit package.json.或者您也可以编辑 package.json。

"start": "ESLINT_NO_DEV_ERRORS='true'  react-scripts start",  
"build": "DISABLE_ESLINT_PLUGIN='true' react-scripts build",

you can disable no-unused-vars eslint rule or change the rule level to warning instead of error .您可以禁用no-unused-vars eslint 规则或将规则级别更改为warning而不是error

More information here: https://eslint.org/docs/rules/no-unused-vars更多信息在这里: https : //eslint.org/docs/rules/no-unused-vars

When I upgraded my create-react-app to v4, it was intimidating to see pages of eslint issues -> errors preventing my app from compiling.当我将我的 create-react-app 升级到 v4 时,看到 eslint 问题页面令人生畏 -> 错误阻止我的应用程序编译。 Not the immediate experience I was expecting using react's fast-refresh :).不是我期望使用 react 的fast-refresh的直接体验 :)。 The change in rules (and error levels), in Eslint 7 are surely the cause. Eslint 7 中规则(和错误级别)的变化肯定是原因。 Although, how the transpiling process started to care about prettier/prettier issues that were previously limited to my linter, remains unclear to me.虽然,转译过程如何开始关心以前仅限于我的 linter 的prettier/prettier的问题,但我仍然不清楚。

Update更新

There are a few things going on.有几件事正在发生。 The Eslint changes (and any extensions such as airbnb) are likely shaking up my mix of errors and warnings, but likely most relevant: CRA v4 no longer uses its own eslint rules, but rather that of the project, ie, the linting rules used in my editor. Eslint 更改(以及任何扩展,如 airbnb)可能会改变我的错误和警告组合,但可能最相关:CRA v4 不再使用自己的 eslint 规则,而是使用项目的规则,即使用的 linting 规则在我的编辑器中。 Prior to the upgrade, CRA's use of the project rules was enabled using EXTEND_ESLINT .在升级之前,CRA 对项目规则的使用是使用EXTEND_ESLINT启用的。 This register is now on by default and no longer something I can set with env in v4 (in my experience anyway).这个寄存器现在默认打开,不再是我可以在 v4 中使用env设置的东西(无论如何根据我的经验)。

Regardless, the quick-fix to get the app to transpile was as follows:无论如何,让应用程序转换的快速修复如下:

  1. git commit my latest changes git commit我的最新更改
  2. run prettier cli: yarn prettier --config ./.prettierrc --write '**/*.{js|jsx}'运行更漂亮的 cli: yarn prettier --config ./.prettierrc --write '**/*.{js|jsx}'
  3. one by one, created a new entry in my .eslintrc to set the blocking error to 'warn' ;一个一个地,在我的.eslintrc中创建了一个新条目,将阻塞错误设置为'warn' eg, added 'no-param-reassign': 'warn' (something I often do in my .reduce routines).例如,添加了'no-param-reassign': 'warn' (我经常在我的.reduce例程中做的事情)。

All in all, the process took me about 5 min.总而言之,这个过程花了我大约 5 分钟。

This got me to a place where I could compile the app whilst giving me time to work through/prioritize what makes sense in this fast-refresh , non-ejected CRA, Eslint v7 version of the app.这让我到了一个可以编译应用程序的地方,同时让我有时间处理/优先考虑在这个fast-refresh 、非弹出的 CRA、Eslint v7 版本的应用程序中有意义的事情。

- E -E

You can add two properties to ESLintPlugin method, inside node_modules\react-scripts\config\webpack.config.js for your project.您可以在项目的 node_modules\react-scripts\config\webpack.config.js 中为 ESLintPlugin 方法添加两个属性。

failOnError: false, emitWarning: true, failOnError:假,emitWarning:真,

 new ESLintPlugin({
        // Plugin options
        extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
        formatter: require.resolve('react-dev-utils/eslintFormatter'),
        eslintPath: require.resolve('eslint'),
        context: paths.appSrc,
        cache: true,
        failOnError: false,
        emitWarning: true,
        // ESLint class options
        cwd: paths.appPath,

在此处输入图像描述

I had a same problem我有同样的问题

this problem have a open issue in CRA (version 4.0) on github这个问题在github上的 CRA(4.0 版)中有一个未解决的问题

I found a temporary solution for this我找到了一个临时解决方案

  1. delete node_modules删除node_modules
  2. change React-Scripts version form 4.0.0 to 3.4.4React-Scripts版本从4.0.0更改为3.4.4
  3. add this SKIP_PREFLIGHT_CHECK=true into .env file将此SKIP_PREFLIGHT_CHECK=true添加到.env文件中
  4. run npm install运行npm install
  5. hope enjoy :)希望享受:)

PS : if .env file dose not exist on your project you can create that in root folder PS:如果您的项目中不存在.env文件,您可以在根文件夹中创建该文件

Now combination of emit + Warning/Error and failOn + Warning/Error is not working for me.现在, emit + Warning/ErrorfailOn + Warning/Error对我不起作用。 In current time I dont set it (stay default), but set quiet = true .目前我没有设置它(保持默认),而是设置quiet = true In this config ESLint shows me errors but dont feil on it在这个配置中,ESLint 向我展示了错误,但不要在上面

I had this same error and here is what worked for me.我有同样的错误,这对我有用。

Along with the error I got the following suggestions in the terminal when I wanted to create an app.除了错误之外,当我想创建应用程序时,我在终端中收到了以下建议。

  1. Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder.
  2. Delete node_modules in your project folder.
  3. Remove "eslint" from dependencies and/or devDependencies in the package.json file in your project folder.
  4. Run npm install or yarn, depending on the package manager you use.

I did all 3 above.以上3个我都做了。 Then I did the following-然后我做了以下 -

I uninstalled eslint
npm uninstall -g create-react-app //uninstall create react app
npm install eslint --save-dev //reinstalled eslint
npm install -g yarn //installed yarn because I was using npm
used yarn to install create react app
yarn create-react-app nameofapp //used yarn to create a new app

when I did npm start, it worked as it seems like yarn was working to patch up/work through the problems.当我执行 npm start 时,它的工作原理似乎是 yarn 正在努力修补/解决问题。

I had to do a bit of trial and error here but finally it worked.我不得不在这里做一些试验和错误,但最终它奏效了。 I am no expert so did not really understand what exactly happened under the hood but this worked for me as yarn took care of the eslint problem.我不是专家,所以并不真正了解引擎盖下到底发生了什么,但这对我有用,因为纱线解决了 eslint 问题。

Replace the third last line in your .eslintrc.json file替换.eslintrc.json文件中的倒数第三行

"no-unused-vars": "error"

with

"no-unused-vars": "warn"

I expect that change to result in a warning instead of an error.我希望该更改会导致警告而不是错误。

Don't forget to restart your text editor or IDE!不要忘记重新启动您的文本编辑器或 IDE!

Disclaimer免责声明
From what I can read in your question, I believe my tip should help.从我在您的问题中可以读到的内容,我相信我的提示应该会有所帮助。 But I haven't tried it myself.但我自己没有试过。

since eslint-loader is now deprecated and eslint-webpack-plugin is now used in create-react-app check the docs , I was able to solve a the issue by adding two options to the eslint-webpack-plugin由于现在不推荐使用eslint-loader并且现在在 create-react-app 中使用了eslint-webpack-plugin检查文档,因此我能够通过向eslint-webpack-plugin添加两个选项来解决问题

after ejecting your react app, add these options to the ESLintPlugin options:弹出你的 react 应用程序后,将这些选项添加到ESLintPlugin选项中:

      new ESLintPlugin({
        // Plugin options
        extensions: ['js', 'mjs', 'jsx', 'ts', 'tsx'],
        formatter: require.resolve('react-dev-utils/eslintFormatter'),
        eslintPath: require.resolve('eslint'),
        context: paths.appSrc,
        failOnError: false,  <== `This one`
        emitWarning: true,  <== `And this one`
        // ESLint class options
        cwd: paths.appPath,
        resolvePluginsRelativeTo: __dirname,
        baseConfig: {
          extends: [require.resolve('eslint-config-react-app/base')],
          rules: {
            ...(!hasJsxRuntime && {
              'react/react-in-jsx-scope': 'error'
            })
          }
        }
      })

in module.rules modify following rule to have在 module.rules 中修改以下规则以具有

failOnError: false,
emitWarning: true,
{
          test: /\.(js|mjs|jsx)$/,
          enforce: 'pre',
          use: [
            {
              options: {
                formatter: require.resolve('react-dev-utils/eslintFormatter'),
                eslintPath: require.resolve('eslint'),
                failOnError: false,
                emitWarning: true,
              },
              loader: require.resolve('eslint-loader'),
            },
          ],
          include: paths.appSrc,
        }

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

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