Skip to content

ouweiya/eslint-plugin-react-zh

 
 

Repository files navigation

eslint-plugin-react

github actions Maintenance Status NPM version Tidelift

针对eslint的React特定的lint规则

安装

npm install eslint eslint-plugin-react --save-dev

也可以全局安装ESLint(使用npm install -g eslint),但不推荐这样做,你使用的任何插件或可共享配置都必须在任何情况下本地安装。

配置(旧版:.eslintrc*

使用我们的预设获取合理的默认值:

    "extends": [
        "eslint:recommended",
        "plugin:react/recommended"
    ]

如果你正在使用React 17的新JSX转换,在你的eslint配置中扩展react/jsx-runtime(在"extends"中添加"plugin:react/jsx-runtime")以禁用相关规则。

你还应指定将在所有插件规则中共享的设置。(更多关于eslint共享设置的信息)

{
    "settings": {
        "react": {
            "createClass": "createReactClass", // 用于使用的组件工厂的正则表达式,
                                               // 默认为 "createReactClass"
            "pragma": "React",  // 使用的Pragma,默认为 "React"
            "fragment": "Fragment",  // 使用的Fragment(可能是<pragma>的属性),默认为 "Fragment"
            "version": "detect", // React版本。"detect"会自动选择你已安装的版本。
                                 // 你也可以使用`16.0`、`16.3`等,如果你想覆盖检测到的值。
                                 // 如果缺失,它将默认为"latest"并发出警告,在未来将默认为"detect"
            "flowVersion": "0.53" // Flow版本
        },
        "propWrapperFunctions": [
                // 用于包装propTypes的任何函数的名称,例如`forbidExtraProps`。如果没有设置,任何包装在函数中的propTypes都将被跳过。
                "forbidExtraProps",
                {"property": "freeze", "object": "Object"},
                {"property": "myFavoriteWrapper"},
                // 用于检查确切的prop包装器的规则
                {"property": "forbidExtraProps", "exact": true}
        ],
        "componentWrapperFunctions": [
                // 用于包装组件的任何函数的名称,例如Mobx的`observer`函数。如果没有设置,这些函数包装的组件将被跳过。
                "observer", // `property`
                {"property": "styled"}, // `object`是可选的
                {"property": "observer", "object": "Mobx"},
                {"property": "observer", "object": "<pragma>"} // 将`object`设置为`settings.react.pragma`的值
        ],
        "formComponents": [
            // 用作<form>的替代品的组件,例如<Form endpoint={ url } />
            "CustomForm",
            {"name": "SimpleForm", "formAttribute": "endpoint"},
            {"name": "Form", "formAttribute": ["registerEndpoint", "loginEndpoint"]}, // 如果需要,允许指定多个属性
        ],
        "linkComponents": [
            // 用作<a>的替代品的组件,例如<Link to={ url } />
            "Hyperlink",
            {"name": "MyLink", "linkAttribute": "to"},
            {"name": "Link", "linkAttribute": ["to", "href"]}, // 如果需要,允许指定多个属性
        ]
    }
}

如果你不使用预设,你将需要指定单独的规则并添加额外的配置。

在插件部分添加"react"。

{
    "plugins": [
        "react"
    ]
}

启用JSX支持。

对于eslint 2+

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

启用你想使用的规则。

    "rules": {
        "react/jsx-uses-react": "error",
        "react/jsx-uses-vars": "error",
    }

可共享的配置

推荐的

此插件导出一个recommended配置,该配置强制执行React的良好实践。

要启用此配置,请在你的.eslintrc配置文件中使用extends属性:

{
    "extends": ["eslint:recommended", "plugin:react/recommended"]
}

查看eslint文档以获取有关扩展配置文件的更多信息。

全部

此插件还导出一个all配置,该配置包含每个可用的规则。 这与eslint:all规则配合得很好。

{
    "plugins": [
        "react"
    ],
    "extends": ["eslint:all", "plugin:react/all"]
}

注意:这些配置将导入eslint-plugin-react并在解析器选项中启用JSX。

配置(新版:eslint.config.js

v8.21.0开始,eslint宣布了一个新的配置系统。 在新系统中,不再使用.eslintrc*eslint.config.js将成为默认的配置文件名。 在eslint v8中,旧系统(.eslintrc*)仍将得到支持,而在eslint v9中,只有新系统将得到支持。

v8.23.0开始,eslint CLI开始查找eslint.config.js所以,如果你的eslint是>=8.23.0,你就完全准备好使用新的配置系统了。

你可能想查看官方的博客文章,

以及官方文档

插件

eslint-plugin-react的默认导出是一个插件对象。

const react = require('eslint-plugin-react');
const globals = require('globals');

module.exports = [
  
  {
    files: ['**/*.{js,jsx,mjs,cjs,ts,tsx}'],
    plugins: {
      react,
    },
    languageOptions: {
      parserOptions: {
        ecmaFeatures: {
          jsx: true,
        },
      },
      globals: {
        ...globals.browser,
      },
    },
    rules: {
      // ... 你想要的任何规则
      'react/jsx-uses-react': 'error',
      'react/jsx-uses-vars': 'error',
     },
    // ... 其他的省略了以简洁为主
  },
  
];

配置共享设置

参考官方文档

settings.react对象的模式将与上述旧配置部分中已经描述的完全相同。

可共享的配置

还有3个可共享的配置。

  • eslint-plugin-react/configs/all
  • eslint-plugin-react/configs/recommended
  • eslint-plugin-react/configs/jsx-runtime

如果你的eslint.config.js是ESM,包括.js扩展名(例如eslint-plugin-react/recommended.js)。注意,下一个semver-major将要求省略这些导入的扩展名。

注意:这些配置将导入eslint-plugin-react并在languageOptions.parserOptions中启用JSX。

在新的配置系统中,plugin:协议(例如plugin:react/recommended)不再有效。 由于eslint不会自动导入预设配置(可共享配置),你需要明确地自己做。

const reactRecommended = require('eslint-plugin-react/configs/recommended');

module.exports = [
  
  reactRecommended, // 这不是一个插件对象,而是一个可共享的配置对象
  
];

你当然可以添加/覆盖一些属性。

注意:我们的可共享配置不预先配置fileslanguageOptions.globals。 在大多数情况下,你可能想要自己配置一些属性。

const reactRecommended = require('eslint-plugin-react/configs/recommended');
const globals = require('globals');

module.exports = [
  
  {
    files: ['**/*.{js,mjs,cjs,jsx,mjsx,ts,tsx,mtsx}'],
    ...reactRecommended,
    languageOptions: {
      ...reactRecommended.languageOptions,
      globals: {
        ...globals.serviceworker,
        ...globals.browser,
      },
    },
  },
  
];

上面的例子与下面的例子相同,因为新的配置系统基于链式。

const reactRecommended = require('eslint-plugin-react/configs/recommended');
const globals = require('globals');

module.exports = [
  
  {
    files: ['**/*.{js,mjs,cjs,jsx,mjsx,ts,tsx,mtsx}'],
    ...reactRecommended,
  },
  {
    files: ['**/*.{js,mjs,cjs,jsx,mjsx,ts,tsx,mtsx}'],
    languageOptions: {
      globals: {
        ...globals.serviceworker,
        ...globals.browser,
      },
    },
  },
  
];

支持的规则列表

💼 在配置中启用。
🚫 在配置中禁用。
🏃 在jsx-runtime配置中设置。
☑️ 在recommended配置中设置。
🔧 可以通过--fix CLI选项自动修复。
💡 可以通过编辑器建议手动修复。
❌ 已弃用。

Name                                  Description 💼 🚫 🔧 💡
boolean-prop-naming Enforces consistent naming for boolean props
button-has-type Disallow usage of button elements without an explicit type attribute
checked-requires-onchange-or-readonly Enforce using onChange or readonly attribute when checked is used
default-props-match-prop-types Enforce all defaultProps have a corresponding non-required PropType
destructuring-assignment Enforce consistent usage of destructuring assignment of props, state, and context 🔧
display-name Disallow missing displayName in a React component definition ☑️
forbid-component-props Disallow certain props on components
forbid-dom-props Disallow certain props on DOM Nodes
forbid-elements Disallow certain elements
forbid-foreign-prop-types Disallow using another component's propTypes
forbid-prop-types Disallow certain propTypes
function-component-definition Enforce a specific function type for function components 🔧
hook-use-state Ensure destructuring and symmetric naming of useState hook value and setter variables 💡
iframe-missing-sandbox Enforce sandbox attribute on iframe elements
jsx-boolean-value Enforce boolean attributes notation in JSX 🔧
jsx-child-element-spacing Enforce or disallow spaces inside of curly braces in JSX attributes and expressions
jsx-closing-bracket-location Enforce closing bracket location in JSX 🔧
jsx-closing-tag-location Enforce closing tag location for multiline JSX 🔧
jsx-curly-brace-presence Disallow unnecessary JSX expressions when literals alone are sufficient or enforce JSX expressions on literals in JSX children or attributes 🔧
jsx-curly-newline Enforce consistent linebreaks in curly braces in JSX attributes and expressions 🔧
jsx-curly-spacing Enforce or disallow spaces inside of curly braces in JSX attributes and expressions 🔧
jsx-equals-spacing Enforce or disallow spaces around equal signs in JSX attributes 🔧
jsx-filename-extension Disallow file extensions that may contain JSX
jsx-first-prop-new-line Enforce proper position of the first property in JSX 🔧
jsx-fragments Enforce shorthand or standard form for React fragments 🔧
jsx-handler-names Enforce event handler naming conventions in JSX
jsx-indent Enforce JSX indentation 🔧
jsx-indent-props Enforce props indentation in JSX 🔧
jsx-key Disallow missing key props in iterators/collection literals ☑️
jsx-max-depth Enforce JSX maximum depth
jsx-max-props-per-line Enforce maximum of props on a single line in JSX 🔧
jsx-newline Require or prevent a new line after jsx elements and expressions. 🔧
jsx-no-bind Disallow .bind() or arrow functions in JSX props
jsx-no-comment-textnodes Disallow comments from being inserted as text nodes ☑️
jsx-no-constructed-context-values Disallows JSX context provider values from taking values that will cause needless rerenders
jsx-no-duplicate-props Disallow duplicate properties in JSX ☑️
jsx-no-leaked-render Disallow problematic leaked values from being rendered 🔧
jsx-no-literals Disallow usage of string literals in JSX
jsx-no-script-url Disallow usage of javascript: URLs
jsx-no-target-blank Disallow target="_blank" attribute without rel="noreferrer" ☑️ 🔧
jsx-no-undef Disallow undeclared variables in JSX ☑️
jsx-no-useless-fragment Disallow unnecessary fragments 🔧
jsx-one-expression-per-line Require one JSX element per line 🔧
jsx-pascal-case Enforce PascalCase for user-defined JSX components
jsx-props-no-multi-spaces Disallow multiple spaces between inline JSX props 🔧
jsx-props-no-spreading Disallow JSX prop spreading
jsx-sort-default-props Enforce defaultProps declarations alphabetical sorting
jsx-sort-props Enforce props alphabetical sorting 🔧
jsx-space-before-closing Enforce spacing before closing bracket in JSX 🔧
jsx-tag-spacing Enforce whitespace in and around the JSX opening and closing brackets 🔧
jsx-uses-react Disallow React to be incorrectly marked as unused ☑️ 🏃
jsx-uses-vars Disallow variables used in JSX to be incorrectly marked as unused ☑️
jsx-wrap-multilines Disallow missing parentheses around multiline JSX 🔧
no-access-state-in-setstate Disallow when this.state is accessed within setState
no-adjacent-inline-elements Disallow adjacent inline elements not separated by whitespace.
no-array-index-key Disallow usage of Array index in keys
no-arrow-function-lifecycle Lifecycle methods should be methods on the prototype, not class fields 🔧
no-children-prop Disallow passing of children as props ☑️
no-danger Disallow usage of dangerous JSX properties
no-danger-with-children Disallow when a DOM element is using both children and dangerouslySetInnerHTML ☑️
no-deprecated Disallow usage of deprecated methods ☑️
no-did-mount-set-state Disallow usage of setState in componentDidMount
no-did-update-set-state Disallow usage of setState in componentDidUpdate
no-direct-mutation-state Disallow direct mutation of this.state ☑️
no-find-dom-node Disallow usage of findDOMNode ☑️
no-invalid-html-attribute Disallow usage of invalid attributes 💡
no-is-mounted Disallow usage of isMounted ☑️
no-multi-comp Disallow multiple component definition per file
no-namespace Enforce that namespaces are not used in React elements
no-object-type-as-default-prop Disallow usage of referential-type variables as default param in functional component
no-redundant-should-component-update Disallow usage of shouldComponentUpdate when extending React.PureComponent
no-render-return-value Disallow usage of the return value of ReactDOM.render ☑️
no-set-state Disallow usage of setState
no-string-refs Disallow using string references ☑️
no-this-in-sfc Disallow this from being used in stateless functional components
no-typos Disallow common typos
no-unescaped-entities Disallow unescaped HTML entities from appearing in markup ☑️
no-unknown-property Disallow usage of unknown DOM property ☑️ 🔧
no-unsafe Disallow usage of unsafe lifecycle methods ☑️
no-unstable-nested-components Disallow creating unstable components inside components
no-unused-class-component-methods Disallow declaring unused methods of component class
no-unused-prop-types Disallow definitions of unused propTypes
no-unused-state Disallow definitions of unused state
no-will-update-set-state Disallow usage of setState in componentWillUpdate
prefer-es6-class Enforce ES5 or ES6 class for React Components
prefer-exact-props Prefer exact proptype definitions
prefer-read-only-props Enforce that props are read-only 🔧
prefer-stateless-function Enforce stateless components to be written as a pure function
prop-types Disallow missing props validation in a React component definition ☑️
react-in-jsx-scope Disallow missing React when using JSX ☑️ 🏃
require-default-props Enforce a defaultProps definition for every prop that is not a required prop
require-optimization Enforce React components to have a shouldComponentUpdate method
require-render-return Enforce ES5 or ES6 class for returning value in render function ☑️
self-closing-comp Disallow extra closing tags for components without children 🔧
sort-comp Enforce component methods order
sort-default-props Enforce defaultProps declarations alphabetical sorting
sort-prop-types Enforce propTypes declarations alphabetical sorting 🔧
state-in-constructor Enforce class component state initialization style
static-property-placement Enforces where React component static properties should be positioned.
style-prop-object Enforce style prop value is an object
void-dom-elements-no-children Disallow void DOM elements (e.g. <img />, <br />) from receiving children

其他有用的插件

License

eslint-plugin-react is licensed under the MIT License.

About

针对ESLint的React特定的lint规则

Resources

License

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%