Eslint most comprehensive configuration templates, unified team from programming practice

With the increase of the project, an urgent need for a unified code specifications of each project, some low-level error strangle in the bud. So hereby incorporated some of the specifications of the current project, and then based on community recommended practices, integrate into the repo . Which integrates React and Nodejs programming specifications, all specifications are based on Airbnb , which broke down the js version and version ts to meet everyone's needs programming.

Another source other normative framework is not the actual project experience, it is not able to round up all the "Dragon Ball", so welcome to contribute in this standard usually used for encoding specifications (as far as possible be based on the airbnb), shared with other community children's shoes.

Eslint ecological dependencies introduced

In the description Eslint configuration before, let's have some dependencies role Eslint configuration of the ecosystem involved, so we party can know why.

The most basic

  1. eslint : The main tool lint code, so everything is based on this package

Parser (parser)

  1. eslint-babel : This package allows you to rely on some experimental features, when still able to spend Eslint syntax checking. Conversely, when you did not use the code is not supported by experimental characteristics Eslint is no need to install this dependency package.

  2. the typescript-eslint @ / Parser : Typescript syntax parser, similar babel-eslintparsers. Corresponding to the parserOptionsconfiguration of the reference official README.

Extended configuration

  1. Airbnb-config-eslint : This package provides ESLint configure all of Airbnb, as an extension of shared configuration, you can modify the cover off some unwanted configuration, the toolkit contains the relevant rules react Eslint of ( eslint-plugin-react with eslint-plugin-jsx-a11y) , so that when installing the dependencies also need to install two plug just mentioned

  2. Airbnb--config-eslint Base : the difference between a package that this package does not contain rules dependent react, typically used to check the server.

  3. -config-JEST-eslint enzyme : JEST and enzyme-specific validation rules to ensure that some of the assertions syntax allows Eslint recognize without issuing a warning.

  4. config-prettier-eslint : will disable all those non-essential or out and prettier rule violations. This allows you to use your favorite shareable configuration, rather than let it get in the way of style choice when using Prettier. Please note that this configuration is only the rule off away, so it's only when used in conjunction with other configuration makes sense.

Plug

  1. plugin-babel-eslint : a plug-in .babel-eslint and babel-eslint used together in the eslint applied Babel has done well, but it does not change the built-in rules to support experimental feature. eslint-plugin-babel re-implement the rules in question, and therefore will not be false misinformation

  2. Import-plugin-eslint : The plug-in you want to support the case for ES2015 + (ES6 +) import / export syntax check, and prevent some import the file path name is misspelled or wrong

  3. -plugin-JSX-eslint A11Y : focus on checking the dependencies JSX element accessible.

  4. Import--the Resolver-eslint webpack : webpack can use configurations to assist eslint resolve, the most useful is the alias, in order to avoid errors of unresolved

  5. Import--the Resolver-eslint the typescript : and eslint-import-resolver-webpack similar, mainly to solve the alias problem

  6. plugin-REACT-eslint : React specific validation rules plug.

  7. JEST-plugin-eslint : Jest specific rule checking Eslint plug.

  8. plugin-prettier-eslint : the plug can be smoothly auxiliary Eslint prettier cooperate with, and as part of the analysis prettier Eslint can be given amendments in the final output. So that when Prettier formatting code, still able to follow our Eslint rules. If you disable all out and code formatting rules associated Eslint words, the plug can better get to work. So you can use eslint-config-prettier disabled out all of the formatting rules related to (time if other effective Eslint rules and prettier on how to code formatting inconsistencies, the error is inevitable)

  9. the typescript-eslint @ / eslint-plugin : Typescript auxiliary Eslint plug-ins.

  10. Promise-plugin-eslint : Promise specification writing check-ins, with some validation rules.

Assist optimize processes

  1. Husky : git command hook-specific configuration.

  2. staged-lint : can be customized to perform a specific command at a particular stage of git.

Prettier

Prettier related packages have a good number, in addition to two listed above, you may also use the following three:

  1. prettier : the original version to achieve defined prettier rules and implement these rules. Support rules reference: Portal

  2. eslint-prettier : enter the code, after the execution of the code prettier then eslint --fix output formatter. Only supports input string.

  3. cli-prettier-eslint : As the name suggests, supports CLI command execution prettier-eslint operation

So much so Prettier toolkit, is what to do with it? Too easy to confuse. Here one paragraph brief:

The most basic is prettier, then you need to go eslint-config-prettier and prettier to disable all the rules out the conflict, so that it can be used eslint-plugin-prettier to rule in a manner consistent eslint formatting code and corresponding prompt proposed changes . To make prettier and eslint together, so was born prettier-eslint this tool, but it only supports input strings of code, does not support reading files, so there has been a prettier-eslint-cli

This is the relationship between the five kits each other. Coupled with the high readability prompted after a little prettier, as shown below:

Eslint profile

  1. env: Predefined global variables need to use those environmental parameters available are: es6, broswer, nodeand so on.

    es6Can make all the features ECMAScript6 addition module (this function is set ecmaVersion version is automatically set to the time 6)

    browserWe will add all the variables such as Windows browser

    nodeAdd all global variables such asglobal

    More Environment Configuration Reference Specifying Environments

  2. extends: Specifies the expanded configuration, configuration support extended recursively, coverage and support aggregation rules.

  3. plugins: Configuring plug-ins that we want Linting rules.

  4. parser: Default ESlint use Espree as a parser, but once we use babel, we need to use babel-eslint.

  5. parserOptions: When we changed the default parser babel-eslint from Espree, we need to specify parseOptions, this is a must.

    ecmaVersion: The default value is 5, can be set to 3,5,6,7,8,9,10 to specify which version of ECMAScript syntax. You may be provided based on the year JS standards, such as 2015 (ECMA 6)

    sourceType: If your code is written in ECMAScript module, the field is configured to module, otherwise script(the default value)

    ecmaFeatures: This object indicates additional language features you want to use

     globalReturn:允许全局范围内的`return`语句
    
     impliedStrict:使能全局`strict`模式
    
     jsx:使能JSX
    复制代码
  6. rules: custom rules, you can overwrite extends configuration.

  7. settings: This field defines the data can be shared among all the plug-ins. In this way, when each rule execution can access this inside-defined data

More configuration options refer to the official documentation Eslint

Eslint configuration file parsing

Introduced so much, a configuration example of our templates to provide eslint-react-js it (instructions are written in a comment the ~):

module.exports =  {
  parser:  'babel-eslint',  // Specifies the ESLint parser
  parserOptions: {
    ecmaVersion: 2015, // specify the version of ECMAScript syntax you want to use: 2015 => (ES6)
    sourceType:  'module',  // Allows for the use of imports
    ecmaFeatures: {
      jsx: true, // enable JSX
      impliedStrict: true // enable global strict mode
    }
  },
  extends:  [
    'airbnb',  // Uses airbnb, it including the react rule(eslint-plugin-react/eslint-plugin-jsx-a11y)
    'plugin:promise/recommended',
    // 'prettier', // Use prettier, it can disable all rules which conflict with prettier
    // 'prettier/react' // Use prettier/react to pretty react syntax
  ],
  settings: {
    'import/resolver': { // This config is used by eslint-import-resolver-webpack
      webpack: {
        config: './webpack/webpack-common-config.js'
      }
    },
  },
  env: {
    browser: true // enable all browser global variables
  },
  'plugins': ['react-hooks', 'promise'], // ['prettier', 'react-hooks']
  rules:  {
    // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
    // e.g. '@typescript-eslint/explicit-function-return-type': 'off',
    "react-hooks/rules-of-hooks": "error",
    "semi": ["error", "never"],
    "react/jsx-one-expression-per-line": 0,
    /**
     * @description rules of eslint-plugin-prettier
     */
    // 'prettier/prettier': [
    //   'error', {
    //     'singleQuote': true,
    //     'semi': false
    //   }
    // ]
  },
};
复制代码

Because we save the code and commit phase will be formatted prettier, so in Eslint disabled lost all configurations with prettier if you need to, you can re-enable off.

Contrast the following about the open prettier and prettier of the difference is not open:

with

The impact of the rules Prettier

So much prettier introduced above, this section briefly describes some important rules prettier of the following:

  1. printWidth: make sure the length of each line of your code will not be more than 100 characters
  2. singleQuote: convert all double quotes single quotes
  3. trailingComma: Ensure that the object after the last property will be a comma
  4. bracketSpacing: automatically add a space between literal objects, such as: {foo: bar}
  5. jsxBracketSameLine: In the last line of multi-line elements JSX additional>
  6. tabWidth: Specifies the width of tab is a few spaces
  7. semi: whether to be added in a statement after each line of code;

More rules please refer to: Options

Let beautiful code deep into the bone marrow -

Save the code when the automatic formatting (Vscode version)

  1. Eslint plug-in installation

  2. Vscode configuration:

    2.1. editor.formatOnSaveIs set to false, to prevent the default file format configuration and Eslint conflict and Prettier

    2.2. eslint.autoFixOnSaveIs set to true, so that when we save each file can automatically fix malformed files.

    As shown below:

Lint-staged

Lint-staged to help you when staging a file format that allows error code is not submitted to your branch.

Why Lint-staged?

Because the code is checked before submitting a final quality control a part of the code, so be lint check before the code is of great significance. This ensures that there are no errors in grammar and style code that is submitted to the warehouse. But on the whole project implementation process Lint will be very inefficient, so the best thing to do is check that the document had been altered. The Lint-staged is doing this.

The ecosystem dependencies we provide the above, in package.jsonthe configuration of the field:

"lint-staged": {
  "**/*.{tsx,ts}": [ // 这里的文件后缀可以修改成自己需要的文件后缀
    "prettier-eslint --write",
    "git add"
  ]
}
复制代码

Use in conjunction with Husky

To make lint-staged can be executed before the change is staged, this time we need the help of git hook functions, and hook functions provide community solution is Husky , the tool provides a git operations performed in front of several stages, such as our this should be checked at the time of the pre-Lint submitted the following configuration:

"husky": {
  "hooks": {
    "pre-commit": "lint-staged"
  }
}
复制代码

So that each will commit time to perform lint operation, as said before, prettier-eslint-cli loads code prettier again after eslint --fix, if not wrong, then it will be directly executed git add, otherwise an error exit.

EditorConfig

Because not all people use VS code, in order to maintain consistency in the same project, such as tab width end of the line or want to have a semicolon, we can use .editorconfig to unify these configurations.

The editor supports EditorConfig list please go here .

The following is a template configuration inside the recommended configuration editorconfig

# EditorConfig is awesome: http://EditorConfig.org

# top-most EditorConfig file
root = true

[*.md]
trim_trailing_whitespace = false

[*.js]
trim_trailing_whitespace = true

# Unix-style newlines with a newline ending every file
[*]
indent_style = space
indent_size = 2
# 保证在任何操作系统上都有统一的行尾结束字符
end_of_line = lf
charset = utf-8
insert_final_newline = true
max_line_length = 100
复制代码

At last

So far Eslint full resolution on a perfect ending, and finally Amway wave eslint-config-Templates , are also welcome to PR.

reference

  1. These tools will help you write clean code
  2. Prettier
  3. Eslint

Guess you like

Origin blog.csdn.net/weixin_33719619/article/details/91366185