eslint 不处理多个 package.json

eslint don't deal with multiple package.json

我的项目有两个package.json

root folder

└ app ---- /public
         └ /styles
         └ /src
         └ package.json
         └ eslintrc.json
         └ webpack.config.js

└ server - /something
         └ /something

└ package.json
└ ...etc

atom 编辑器显示 lint 错误

import React from 'react';
// 'react' should be listed in the project's dependencies. Run 'npm i -S react' to add it (import/no-extraneous-dependencies)

在package.json

"dependencies": {
  "@types/chart.js": "^2.6.8",
  "@types/react": "^16.0.10",
  "@types/react-dom": "^16.0.1",
  "bootstrap": "^4.0.0-beta",
  "chart.js": "2.6.0",
  "font-awesome": "^4.7.0",
  "history": "4.7.2",
  "jwt-decode": "^2.2.0",
  "prop-types": "^15.6.0",
  "react": "^15.6.1",
  "react-chartjs-2": "2.6.1",
  "react-dom": "^15.6.1",
  "react-router-dom": "4.2.2",
  "react-transition-group": "^1.2.0",
  "reactstrap": "^4.8.0",
  "simple-line-icons": "^2.4.1"
},

并在 eslintrc.json

module.exports = {
  "extends": "airbnb",

  "env": {
     "browser": true,
     "node": true
   },

  "rules": {
     "no-mixed-operators": [2, { "allowSamePrecedence": true }],
     "react/no-find-dom-node": 1,
     "react/no-string-refs": 1,
     "react/no-unused-prop-types": 1, // TODO: enable
     "jsx-a11y/no-static-element-interactions": 1, // TODO: enable
     "no-plusplus": 1, // TODO: enable
     "no-console": 0, // TODO: enable
     "no-alert": 0,
     "max-len": ["error", 120],
     "no-underscore-dangle": ["error", { "allow": ["_isMounted"] }],
     "import/no-extraneous-dependencies": ["error", {"devDependencies": true}],
  },
};

我认为 eslint 将根文件夹中的 package.json 识别为标准。 但我希望它忽略根文件夹中的 package.json 并识别 src 文件夹中的 package.json。

我该怎么办?

我自己解决了这个问题。

在 .eslintrc.json

中添加了 "packageDir": "./src"
"rules" : {
   ""import/no-extraneous-dependencies": ["error", {"devDependencies": true, "packageDir": "./src"}],

这可能无关紧要,但我首先要注意的是,您可能需要将 ESLint 配置从 eslintrc.json 重命名为 .eslintrc.json(名称前加一个点)。可能不是问题的根源,但可能会干扰分层解析。您可以在此处查看多种配置扩展格式:https://eslint.org/docs/user-guide/configuring#configuration-file-formats.

具体关于 import/no-extraneous-dependencies 规则,我认为您可能正在寻找的配置选项是 packageDir。在他们的 repo 中引用文档:

Also there is one more option called packageDir, this option is to specify the path to the folder containing package.json and is relative to the current working directory.

"import/no-extraneous-dependencies": ["error", {"packageDir": './some-dir/'}]

希望对您有所帮助!

来源:

https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-extraneous-dependencies.md