preface

A big problem for team management in multi-person collaborative development projects is that it is inevitable that each developer will have different coding habits and different code styles. In order to make the code highly available and maintainable, how to unify and standardize the code as far as possible in project management?

  • Document convention – Inculcate, ask for more blessing?
  • A lot of CodeRevice, huh?

Obviously, this kind of lack of real-time feedback and delayed solution will cause high communication cost, and the final result is often not ideal… The ideal approach is to automate the solution at the project engineering level with tools that can be flexibly configured.

On the other hand, if you look carefully, you will find that whether it is open source project or mature team project, you will find more and more configuration files in the root directory of the project, which is a manifestation of the rapid evolution of the front-end project, gradually improving and robust. And for us, we can’t be silly.

Today, we will analyze the related coding style, code specification

,

,

These are several common configuration functions.

With the combination of EditorConfig+Prettier+ESLint, the project can check, constrain, beautify code during the development process, and unify the coding style through the unified convention configuration. In addition, it can save a lot of communication costs, expose code defects in advance, and reduce the risk of second code modification in the later period.

To summarize:

  • EditorConfig: Write code across editors and ides to maintain a consistent simple coding style;
  • 13, Prettier: A tool for formatting code, Prettier
  • ESLint: for code quality checks, coding style constraints, etc.

Of course, they all have their applications, but let’s take a look at them next, with a focus on ESLint.

EditorConfig

EditorConfig helps multiple developers working on the same project maintain a consistent coding style when used across multiple editors and ides.

The EditorConfig project contains a file format for defining encoding styles and a collection of text editor plug-ins that enable the editor to read the file format and follow the defined styles.

Interpretation of the

  1. Relies on editor IDE support

Some editors integrate support for EditorConfig by default, such as Webstorm, IntelliJ IDEA, etc. Other editors need to be supported by installing plug-ins: Visual Studio Code, Atom, etc.

Visual Studio Code:

  1. Supports multiple file formats

The editor reads a file format that matches and follows the rules defined by the configuration file;

  1. Nearby principle

When a file is opened, the EditorConfig plug-in looks for a file named.editorConfig in the directory of the opened file and in each parent directory. If you reach the root file path or find an EditorConfig file with root = true, the search for the. EditorConfig file stops. The configuration rule closest to the file takes effect and has a higher priority. Generally, you can set a configuration file in the root directory.

  1. The configuration file .editorconfig

Define rule configurations to avoid common code inconsistencies and ugly DIFFs. For example, common configuration items:

# http://editorconfig.org
root = true

#instructions
#Set file encoding to UTF-8;
## Replace tabs with two Spaces;
## Delete trailing whitespace characters when saving;
#Add a blank line at the end of the file;
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

[Makefile]
indent_style = tab
Copy the code

More information can be found on the official website.

Of course, as we’ve seen, EditorConfig has less to do with configuring our editor, and simple rules for writing code, than meets the needs of the project;

Prettier

Prettier is a code formatting tool that was born in 2016 and quickly became popular. -. -prettier only cares about formatting and doesn’t have syntax checks like Lint does for Prettier. It enforces a consistent code presentation format by parsing the code and matching its own set of rules. It has a great advantage in beautifying code, and can be used with ESLint as a nice addition to the ESLint formatting base.

So how to use it?

  1. Use alone, with editor IDE for code formatting;
  2. Use with ESLint, etc. They are discussed in detail in ESLint below and won’t be repeated here;
1. Use alone, cooperate with editor IDE for code formatting

Take VSCode as an example, install the Prettier plug-in first.VSCode The built-in code formatting tool “VSCode” can be specified as “Prettier” to take over. The “Prettier” is displayed in the lower right corner. You can configure the triggering mechanism of formatting by yourself: formatting during line feed, formatting during file saving, or triggering by shortcut keys.

My habit is to use shortcuts to manually trigger formatting.

When formatting does not take effect in the editor, you can use the.settings.jsonCheck the corresponding file format specified formatter and adjust can:In the VSCode editor, when triggering file formatting, the formatting code can be automatically embellished according to the configuration;

Configuration items:

You can change the general configuration in VSCode preferences – Settings – extensions or in.settings.json; Of course, the prettierrc can be set in the root directory of a project.

For example, the following configuration:

{
  // Set mandatory single quotes
  "singleQuote": true.// Add commas to non-trailing lines of multi-line array es5 objects, arrays, etc
  "trailingComma": "es5".// The maximum width of each row is 100
  "printWidth": 100.// Set no semicolon at the end of the statement
  "semi": false.// Use single quotes in JSX
  "jsxSingleQuote": true,}Copy the code

The effective policy of the final formatting is also based on the proximity principle, which matches the configuration file of the nearest parent directory of the target file step by step. The closer the configuration file is, the higher the priority is.

ESLint

ESLint is a plug-in detection tool that identifies and reports code by matching rule patterns in JavaScript code. Its purpose is to ensure the consistency of code specifications and to detect code problems in time and avoid errors in advance. ESLint is concerned with code quality, checking for code style and indicating code that doesn’t conform to the style specification. In addition, ESLint also has some code formatting capabilities.

To understand ESLint, follow the instructions on the ESLint website.

Lint History

ESLint was originally an open source project created by Nicholas C. Zakas (JavaScript advanced programming author) in June 2013. Its goal is to provide a plug-in javascript code detection tool.

JSLint->JSHint->ESLint/TSLint;

  • JSLint, the earliest version of the Lint tool, does not support flexible extension and configuration and must accept all of its rules.
  • JSHint builds on JSLint, giving developers a lot of freedom, but not to add custom rules.
  • Zakas created ESLint because he felt that JSHint at the time was limited to adding custom rules.
  • ESLint quickly took off after ES6 came along. Because OF ES6’s new syntax, JSHint won’t be supported for a while, and ESLint only needs a proper parser and extended validation rules to be able to do Lint checks. At this point, Babel developed the Babel-ESLint parser to be compatible with ESLint, providing support while also making ESLint the fastest Lint tool to support ES6 syntax.

About TSLint(maintenance stopped)

Kids who have worked with TypeScript will be familiar with TSLint, which is launched and maintained by the TypeScript team.

However, as of January 2019, TSLint is slowly being deprecated and will be gradually migrated to ESLint as a code checking tool, according to TSLint’s official announcement. As for the reasons for stopping maintenance, one is that the ESLint community is more active, more sophisticated, and more supportive of ESLint than TSLint. The second is to find architectural performance problems with the way TSLint’s rules work while iterating continuously to support new features, as opposed to ESLint’s more efficient architecture.

Here’s the kicker: You’ll find many TypeScript projects that use TSLint as a code checking tool without migrating, even though updates have been officially suspended for a long time. If your project is still using TSLint, migrate to ESLint as soon as possible for long-term project maintenance and a better TS code checking experience.

JSHint, TSLint, ESLint, Prettier Npm

So what’s the point of ESLint?

Code review is a static analysis, often used to look for problematic patterns or code, and does not depend on specific coding style. For most programming languages there is code checking, and generally the compiler has a built-in checking tool.

JavaScript is a dynamic and weakly typed language, which is prone to errors in development. Because the program is not compiled, finding errors in JavaScript code often requires constant debugging during execution. Something like ESLint allows programmers to find problems while coding rather than while executing.

Unlike other programming languages such as Java, JavaScript is a weakly typed dynamic language. Due to the lack of a compile phase, errors that could have been discovered during compilation are not discovered until run time, which makes debugging and early detection of hidden problems more difficult. Static analysis is performed before the code is deployed and run to find errors and irregularities.

So why would you need a Lint tool for code checking when TypeScript already detects many problems at compile time? TypeScript focuses on type checking, not code style.

To summarize the functions and benefits of ESLint:

  • Check for grammar errors to avoid low-level bugs;

Examples include API syntax errors, using undefined variables, and changing const variables

  • Unified team code style

For example, use TAB or space, use single or double quotation marks, etc

  • Make sure your code follows best practices

For example, you can use the eslint-config-Standard configuration package to extend the style guide for popular best practices in the community.

This can greatly improve the efficiency, readability, and maintainability of your code when working with multiple people on a project.

ESLint characteristics

All rules of ESLint are designed to be pluggable

Each validation rule is independent and can be turned on or off individually (nothing can be deemed “too important to turn off”), and the result can be set to either a warning or an error. When the rules are written, each rule is a separate file and its corresponding formatting method.

ESLint is fully configurable

ESlint is designed to be fully configurable. In addition to rules being pluggable, you can write custom rules, introduce community rule configuration sets, plug-ins, etc., making ESlint more tailored to the specific needs of each project. React syntax is supported with the ESlint-plugin-React configuration package extension. Support for typescript syntax and validation with @typescript-eslint/ Parser parsers;

ESLint is written using Node.js

Easy to install and have a fast operating environment in front end projects; Ease the barrier for developers to write custom rules;

ESLint converts source code to AST before parsing

ESLint uses Esprima to parse source code into an AST to analyze patterns in the code, then identifies and reports the collected code information through matching rule definitions. While one more transformation layer is slightly less efficient, the benefit of ESLint is that you can use arbitrary rules to detect whether the AST is as expected, which makes ESLint highly scalable.

Supported configuration file formats

ESLint supports configuration files in several formats:

  • JavaScript– use.eslintrc.jsIt then outputs a configuration object.
  • YAML– use.eslintrc.yaml.eslintrc.ymlTo define the configuration structure.
  • JSON– use.eslintrc.jsonTo define the structure of the configuration, ESLint’s JSON file allows JavaScript style comments.
  • (deprecated)– use.eslintrcWhich can be either JSON or YAML.
  • package.json– inpackage.jsonCreate aeslintConfigProperty, where you define your configuration.

If there are multiple configuration files in the same directory, ESLint will only use one. The priority order is as follows:

  1. .eslintrc.js
  2. .eslintrc.yaml
  3. .eslintrc.yml
  4. .eslintrc.json
  5. .eslintrc
  6. package.json

When there are multiple cascading configurations in the project, the proximity principle is still adopted as a high priority.

Configuration File Description

Rules- The enabled Rules and their respective error levels

ESLint comes with a number of rules. You can use comments or configuration files to modify the rules you want to use in your project. To change a rule setting, you must set the rule ID to one of the following values:

  • "off"0– Turn off rules
  • "warn"1– To enable the rule, use the warning level error:warn(Will not cause the program to exit)
  • "error"2– To enable the rule, use the error level error:error(When triggered, the program exits)

Globals- Configure additional global variables

When ESLint is enabled, the no-undef rule will warn when an undefined variable is accessed in the current source file. Sometimes, we need to access global variables in other files and make sure that the values are available. You can then define global variables in ESLint so that ESLint does not issue warnings.

  • Use comments to specify global variables in the following format:
/* global var1, var2 */
Copy the code

This defines two global variables, VAR1 and VAR2. If you want to optionally specify that these global variables can be written (rather than just read), then you can set them with a “writable” flag:

/* global var1:writable, var2:writable */
Copy the code
  • Passed in the configuration fileglobalsConfigure the property Settings, for each global variable key, to set the corresponding value to"writable"To allow overwriting variables, or"readonly"Overwriting variables is not allowed. Such as:
// .eslintrc.js
"globals": {
  "var1": "writable"."var2": "readonly"
}
Copy the code

Environments – Specifies the environment in which the script is run

Each environment has a specific set of predefined global variables. Such as brower, node environment variables, ES6 environment variables, etc.

'env': {
  'browser': true.'commonjs': true.'es6': true
},
Copy the code

Plugins – third party plug-ins

ESLint supports the use of third-party plugins by first downloading and installing the plugins to be introduced into the project, and using the plugins keyword to store the list of plug-in names in the configuration file. Plugin names can omit the eslint-plugin- prefix.

 plugins: ['react'.'babel'].// eslint-plugin-react eslint-plugin-babel
Copy the code

Extends from

A configuration file can be inherited from rules enabled in the underlying configuration.

 extends: ["eslint:recommended"."plugin:prettier/recommended"].Copy the code

Configure the code comment mode

Sometimes, when we need to ignore ESLint’s rule checks in code, we can do this by adding comments to the code. You can specify that some or all of ESLint’s rule checks are on/off for an entire file, a line, or a block.

/* eslint-disable */-- Disable all rules placed at the top of the file without checking the entire file range/* eslint-disable no-alert, no-console */Disable certain rules// eslint-disable-line -- disables the rule on the current line
// eslint-disable-next-line -- disable the rule on the next line
Copy the code

Specific reference: eslint.bootcss.com/docs/user-g… ;

Using ESLint

Install ESLint

ESLint can be installed in the current project or globally, but due to differences between projects, we usually install it in the current project. Installation:

yarn add --save-dev eslint
Copy the code

Install the plug-in and parser

If the project uses TypeScript and React, install:

// We need to install @typescript-eslint/parser instead of the default Espree parser. Yarn add --save-dev typescript@typescript-eslint /parser // Install the Eslint-plugin-react configuration package to extend support for react syntax; Install @typescript-eslint/eslint-plugin to provide additional TS syntax rules yarn add --save-dev eslint-plugin-react@typescript-eslint /eslint-pluginCopy the code

Install other plug-ins and parsers as required.

Creating a Configuration file

Let’s create an.eslintrc.js in the project root directory with the following content:

module.exports = {
    parser: '@typescript-eslint/parser'.plugins: ['react'.'@typescript-eslint'].rules: {
        // Disable var
        'no-var': "error".// Use interface instead of type
        '@typescript-eslint/consistent-type-definitions': [
            "error"."interface"]}}Copy the code

Used on the shoulders of giants

There are many good rule sets in the front end community, and what we need to do is to stand on the shoulders of the giants and build a rule configuration that works for us and our team based on the existing rule set. Slowly build your own or company’s rule configuration by studying others’ excellent rule sets;

ESLint in this article covers only some of the important concepts and basic uses. ESLint rules and configurations contain a lot of content, and if you want to use it well, it’s worth the effort to study it yourself.

Q&A

1. How can I easily start using ESLint without changing the previous code as much as possible?

If you’re using GIt to manage your project code, you can use husky + Lint-Staged (KISS) + Prettier to force validation, format, and fix code when GIt commits, and only process the files you commit.

This pre-commit phase incremental verification mode is used to avoid the impact on the old code; This way can steadily improve the old project;

2. How can THE configurations of Prettier and ESLint conflict?

Perttier rules are used for code formatting while ESLint is used for code validation. If the same rule is not configured in the same way, conflicts often occur.

For example, esLint fixes the string to “single” or “double” quotes. After editing the file again, saving (Prettier) automatically formats the “Prettier” but changes it to “double” quotes again, causing code verification exceptions.

Solution 1: Modify the configuration of eslintrc or prettierrc to make them consistent.

Solution 2: Disable rules for ESLint and Prettier that conflict. Use Prettier instead of ESLint to format; Install the eslint-config-prettier plug-in configuration set to the end of the eslinTRc rule. The ESLint command disables rules that conflict with Prettier. Install the eslint-plugin-prettier plug-in, use prettier to format code, and mark the inconsistencies. The two packages can be used together to format files using Prettier when running ESLint –fix.

For specific configuration and usage, please consult and explore by yourself;

conclusion

The introduction of ESLint, Prettier, and EditorConfig requires the sacrifice of coding freedom for some developers to ensure the consistency of team members’ code styles, thus improving code readability and maintainability. Make the project better managed and the cooperation between members smoother.

Even if you don’t think about team development, you can gradually establish good development practices that will take a long time for your own success.

Of course, we should also be aware of the limitations of the tool:

ESLint and others address team development specification issues, not other issues such as coding ability, code justification, etc., and are a weak part of engineering.

There are times when the team sets particularly strict rules for validation, and the results are collected every time the code is submitted as an important indicator of code quality. Personally, I think this method can quantify some code quality assessment problems, but it is too formalistic. However, liao is better than nothing.

  1. Rules that are too strict limit the flexibility of the code. Each rule should be open to discussion, and it is up to the team to open it;
  2. Language or framework If a writing is prohibited, it should be eliminated at source; It has to be there for a reason;
  3. ESLint is not a magic pill. Best code practices often lie in exploring and constantly updating;

Second, the rapid technological innovation, previously thought of the criteria may not be applicable to the present, to keep the mentality of continuous adjustment and follow up the optimization of action;

3. Don’t be an obsessive about strict coding. It’s not a goal, it’s just a way to make it easier to manage projects and free ourselves from complex team projects.

Rather than relying solely on the tool’s rule validation, let them help us develop good coding habits, develop code quality awareness, and guide us to write better code, rather than relying on it.

The last

Article links – language finch: www.yuque.com/nowthen/lon… ;

Writing is not easy, feel good, or helpful children’s shoes, welcome more star;

Your encouragement is a wisp of spring breeze on my way forward