As projects continue to increase, there is an urgent need to unify the code specifications of each project, and nip some low-level errors in the bud. Therefore, we hereby combine some of the specifications used in the current project with the specifications recommended by the community into this REPO. It integrates the React and Nodejs programming specifications, all of which are based on Airbnb. The js version and TS version are subdivided to meet your programming needs.

In addition, the code specifications of other frameworks do not have actual project experience, so we cannot collect all “Dragon balls”. Therefore, we welcome everyone to contribute the standard code specifications used in daily life (try to be based on Airbnb), and share them with other children in the community.

Introduction to Eslint ecological dependency packages

Before explaining Eslint configurations, let’s take a look at some of the dependency packages involved in the Eslint configured ecosystem so we can understand why.

The most basic

  1. Eslint: The main tool for Lint code, so everything is based on this package

The parser (parser)

  1. Babel-eslint: This dependency package allows you to use some experimental features while still using ESLint syntax checks. On the other hand, you don’t need to install dependencies if your code doesn’t use experimental features that Eslint doesn’t support.

  2. @typescript-eslint/parser: a parser for typescript syntax, similar to the babel-eslint parser. Refer to the official README for the configuration of parserOptions.

Extended configuration

  1. eslint-config-airbnb: The package provides all of Airbnb’s ESLint configurations. As an extended shared configuration, you can change and override some unwanted configurations. The toolkit includes the react related Eslint rules (ESlint-plugin-react and ESlint-plugin-jsX-a11y), so installing this dependency package also requires installing the two plugins mentioned above

  2. Eslint-config-airbnb-base: This dependency package differs from the previous one in that it does not contain react rules and is generally used for server-side checking.

  3. Eslint-config-jest-enzyme: Validation rule for jest and enzyme that ensures that certain assertion syntax can be recognized by ESLint without warning.

  4. Eslint-config-prettier: Disables all rules that aren’t necessary or conflict with Prettier. This lets you use your favorite shareable configuration without letting its style selection get in the way of using Prettier. Note that this configuration only turns the rule off, so it only makes sense when used with other configurations.

The plug-in

  1. Eslint-plugin-babel: A plug-in that works with babel-esLint. Babel-eslint does a good job of applying ESLint to Babel, but it can’t change the built-in rules to support experimental features. Eslint-plugin-babel reimplements the rule in question so that some error messages are not misreported

  2. Eslint-plugin-import: This plugin wants to support validation of the ES2015+ (ES6+) import/export syntax and prevent misspelled file paths or incorrect import names

  3. Eslint-plugin-jsx-a11y: This dependency package focuses on checking the accessibility of JSX elements.

  4. Eslint-import-resolver-webpack: Webpack configurations can be used to assist ESLint resolution, most usefully with aliases, to avoid unresolved errors

  5. Eslint-import-resolver-typescript: similar to eslint-import-resolver-webpack, eslint-import-resolver-typescript resolves alias problems

  6. Eslint-plugin-react: react-specific validation rule plug-in.

  7. Eslint-plugin-jest: Jest-specific esLint rule verification plug-in.

  8. Eslint-plugin-prettier: This plug-in helps ESLint work smoothly with Prettier, parsing prettier as part of ESLint, and editing the final output. So when Prettier formats code, she still follows our Eslint rules. The plugin works better if you disable all Eslint rules related to code formatting. So you can disable formatting rules by using eslint-config-prettier (an error is inevitable if prettier does not conform to a valid ESLint rule on how code is formatted)

  9. @typescript-eslint/eslint-plugin: Plugins for typescript to assist ESLint.

  10. Eslint-plugin-promise: The promise specification is written as a check plug-in, with some validation rules.

Auxiliary optimization process

  1. Husky: git command hook specific configuration

  2. Lint-staged commands can be customized to execute certain commands during certain Git phases.

Prettier

Prettier there are several packages associated with Prettier, but you might use the following three in addition to the two listed above:

  1. Prettier: The original implementation that defines prettier rules and implements them. Supported rule reference: portal

  2. Prettier-eslint: Input code, prettier, eslint –fix Output formatted code Only strings are supported.

  3. Prettier-eslint-cli: As the name implies, the CLI can be used to perform prettier-eslint

So what was the relationship between Prettier’s toolkit? It’s so confusing. Here is a brief introduction in one paragraph:

The most basic is prettier, then you need eslint-config-prettier to disable all rules that conflict with Prettier, In this way, eslint-plugin-prettier can be used to format code in a way that conforms to ESLint rules and suggest changes. Prettier-eslint To marry Prettier and esLint, the tool prettier-esLint was born, but it only supports typing code strings, not reading files, hence prettier-eslint-CLI

This is how the five toolkits relate to each other. Prettier, prettier, prettier, prettier

Eslint configuration files

  1. Env: Predefined global variables required by the environment. The available parameters are es6, Broswer, node, and so on.

    Es6 enables all ECMAScript6 features except modules (this is automatically enabled when ecmaVersion is set to 6).

    Browser will add all browser variables such as Windows

    Node adds all global variables such as global

    Refer to Specifying Environments for more environment configuration

  2. Extends: Specifies the configuration of an extension that supports recursive extension, overwriting and aggregation of rules.

  3. Plugins: Configure the plugins that we want Linting rules for.

  4. Parser: By default, ESlint uses Espree as the parser, but once we use Babel, we need to use babel-esLint.

  5. ParserOptions: When we change the default parser from Espree to babel-eslint, we need to specify parseOptions, which is mandatory.

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

    SourceType: This field is configured to module if your code is written in an ECMAScript module, script otherwise (default)

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

    GlobalReturn: Allows global 'return' statements impliedStrict: enables global 'strict' mode JSX: Enables JSXCopy the code
  6. Rules: Custom rules that override the configuration of extends.

  7. Settings: This field defines data that can be shared across all plug-ins. This allows each rule execution to access the data defined within it

Refer to the official documentation Eslint for more configuration options

Eslint configuration file parsing

Eslint-react-js configuration example: eslint-react-js configuration example:

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
    / /}
    // ]}};Copy the code

Because prettier is formatted during save and commit code, Eslint disables all configuration for Prettier, so you can disable it again if you want.

Prettier not prettier when prettier is turned on

and

Prettier affects rules

Prettier having said so much prettier, this section introduces the following important rules for prettier:

  1. PrintWidth: Make sure your code is no longer than 100 characters per line
  2. SingleQuote: Converts all double quotes to single quotes
  3. TrailingComma: Ensures that the last attribute of an object is followed by a comma
  4. BracketSpacing: Automatically adds Spaces between object literals, such as {foo: bar}
  5. JsxBracketSameLine: Append the last line of a multi-line JSX element >
  6. TabWidth: Specifies that the width of a TAB is several Spaces
  7. Semi: Whether to add after each line of declared code;

For more rules, see Options

Let beautiful code deep into the bone marrow ~

Automatic formatting when saving code (Vscode version)

  1. Install the Eslint plugin

  2. Vscode configuration:

    2.1.editor. formatOnSave is set to false in case the default file formatting configuration conflicts with Eslint and Prettier

    2.2.eslint. AutoFixOnSave is set to true so that we can automatically fix the incorrect formatting of files every time we save them.

    The diagram below:

Lint-staged

Lint-staged helps you to have misformatted code not submitted to your branch while you’re staging files.

Why Lint-Staged?

Because checking before committing code is the last piece of code quality control, it makes sense to check lint before committing code. This ensures that no incorrect syntax and code styles are submitted to the repository. But it would be inefficient to run Lint on an entire project, so the best thing to do is check the file that was changed. Lint-staged does just that.

Configure this field in package.json based on the ecosphere dependency packages we provided above:

"Lint-passage ": {"**/*.{TSX,ts}": [// Passage suffixes "prettier-eslint --write", "git add"]}" passage suffixes ": {"**/*.{TSX,ts}": [// Passage suffixes "prettier-eslint --write", "git add"]}Copy the code

Used in combination with Husky

To get Lint-staged before change has been passively executed, git hooks are required. Husky is a community solution that provides git operations that can be performed several stages ahead of passage. For example, this time we will have lint checked during pre-commit. The configuration is as follows:

"husky": {
  "hooks": {
    "pre-commit": "lint-staged"
  }
}
Copy the code

Prettier-eslint-cli prettier code before esLint –fix, git add if there is no error, git add if there is no error

EditorConfig

Not everyone uses VS Code, so in order to be consistent across the same project, such as the width of a TAB or whether to have a semicolon at the end of a line, we can use.editorConfig to unify these configurations.

A list of editors that support EditorConfig can be found here.

Here are the recommended editorConfig configurations in the template configuration

# 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
#Ensure consistent end-of-line characters on any operating system
end_of_line = lf
charset = utf-8
insert_final_newline = true
max_line_length = 100
Copy the code

The last

So that’s the end of Eslint’s full parsing, and finally, an Amway wave of ESLint-config-templates.

reference

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