Preface: Why is a project specification needed

The way we learn programming is different, and the understanding of knowledge is also different. After programming day by day, everyone has developed their own code habits and understanding.

Differences in code habits and understanding result in a wide variety of “canonical” code in teams. When you look at your code, you might think your code looks pretty standard, just a little messy. But when a team member looks at your code, he’s probably thinking: WTF, how does his code look like this? This style of code is like a salad recipe automatically formatted by a corporate lawyer using excel specifications.

This difference leads to inefficient team collaboration and affects the robustness and maintainability of projects. Therefore, we need to standardize the code style. This specification not only keeps the code style consistent, but also can detect some errors and bugs before the code runs, improving the efficiency of collaborative development.

Javascript, the most commonly used language by front-end developers, was originally designed to handle simple web interactions and is a weakly typed, prototype-based language.

Javascript has a flexibility that no other language has, and this flexibility makes code more efficient, but it also makes code writing more arbitrary. In addition, Javascript’s implicit type conversion rules are confusing, allowing functions with the same name to be repeatedly defined, which increases the potential for hidden problems in the code.

Bad joke: The difference in thickness between the definitive Javascript guide and the Javascript language essence.

Finding these potential errors before the code is submitted for testing can greatly reduce the stress on testers and the cost of debugging software projects. However, Javascript as an interpreted language, the interpreter is embedded in the corresponding client, which is powerless, this task can only be completed by special code inspection tools.

In the following sections, I’ll address each of these issues, first with a tool to address them, then with a step-by-step approach to team specification and error predetection with the tool, and finally with a single command to integrate these complex steps to minimize the barriers to use.

Eslint and Prettier

lint

Lint is one of the most famous C language tools. It was developed by SteveJohnson of bell LABS in 1979 based on PCC(PortableC Compiler) for static code analysis and is generally provided by UNIX systems.

Lint is used to check for potential errors in C programs, including (but not limited to) suspicious type combinations, unused variables, unreachable code, and unportable code. Lint produces a set of diagnostics that programmers need to read carefully from beginning to end. The benefits of using Lint are:

  1. It checks for errors missed by the compiler;
  2. Can be associated with many files for error checking and code analysis, with a strong flexibility

Lint is probably the ancestor of lint.

Eslint

A guy named Nicholas C. Zakas released a Lint tool for Javascript in 2013. Javascript is also called ECMAScript (ES for short), so the tool is called ESlint.

ESLint is a tool for identifying and reporting pattern matches in ECMAScript/JavaScript code with the goal of ensuring code consistency and avoiding errors.

Eslint can catch syntax errors and potential bugs before the code is even run, greatly reducing the stress on testers and debugging costs for software projects. Also, Eslint allows developers to define their own code specifications through Rules, making it ideal for team code specifications.

Prettier

Prettier Prettier is a code formatting tool that detects formatting problems in code, such as single line length, TAB length, Spaces, comma expressions, and so on. While Prettier tends to unify the coding style of a project, ESlint tends to control the code quality of a project, while Prettier tends to unify the coding style of a project.

Before the –fix parameter was introduced, ESlint did not automate formatting code, and the only way to do bulk formatting for formatting problems was with a tool like Prettier. Also, Prettier is more comprehensive than ESlint in detecting code styles, so the two are usually used together.

Common standard specifications

NPM I eslint prettier -g Install ESLint and Prettier globally before introducing the specification, using the NPM I eslint prettier -g command, which will be used in subsequent tutorials.

Specification recommended by ESlint

ESlint does not turn on any custom rule validation by default. It only detects bad ES5 syntax and standard syntax errors, such as const ES6 syntax, as well as puzzling semicolons (see figure below).

The specification recommended by ESlint will be enabled when we add the eslintrc.js file to the project directory and write the following:

module.exports = {
  root: true.extends: 'eslint:recommended'
};
Copy the code

In the ESlint recommendation, there are some built-in rules, such as throwing errors for variables that are not used after being defined, as well as using constants as loop conditions (see figure below).

The recommended specification of ESlint can avoid some errors, such as the above two errors can be detected and resolved before running, refer to ESlint Recommend for more details.

standard

Standard is a stricter specification derived from ESlint Recommend. There are about 88 differences between “recommended” and “recommended” in this specification. “recommended” is usually “off”, while “standard” is “error”, such as a single line of code with a space anda semicolon ending is prohibited.

The following code does not report an error under a recommended specification, whereas it would report an error in a Standard specification.

It specification

Standard specification

To install the standard plugin, run the NPM I standard eslint-plugin-standard eslint-config-standard -d command, and write the following to the eslintrc.js file: The Standard specification will be enabled:

module.exports = {
  root: true.extends: ['standard']};Copy the code

Standard is more restrictive than recommended and has some limitations on code style. However, its user groups are also more, there is no lack of some familiar. (As shown below)

For details about the specification, see ESlint Standard.

airbnb

The Airbnb specification is the strictest ESlint specification, with the following notable differences:

  1. Semicolons are mandatory by default, and ESLint does not add semicolons by default
  2. Instead of using a for loop, we recommend using the array’s own API for traversal.
  3. Use the arrow function notation when you must use a function expression (or pass an anonymous function).

In addition to these, there are more strict rules, check out the Airbnb specification.

Configure Eslint + Prettier in the project

Because Eslint and Prettier share some of the same rules, a weird thing happens when the same rule is not set: code formatted using Prettier cannot pass Eslint.

ESlint + Prettier for example, a front-end code specification is used to configure a complete ESlint + Prettier specification for a project.

Configuration. The eslintrc. Js

Let’s create a new eslintrc.js file and write the following as our initial configuration. (below)

module.exports = {
  root: true // Indicates that the file is the root configuration file
};
Copy the code

In the example code in the previous chapter, we found that ESLint only recognizes ES5 syntax by default, so we first configure the env attribute to make ESLint support ES6 syntax, and we set the environment to either Browser (browser) or Node (below).

module.exports = {
  root: true.env: {
    browser: true.node: true.es6: true,},extends: 'eslint:recommended'
};
Copy the code

No additional Settings are required if you use Standard, which supports the latest ECMAScript features. Experimental features require the addition of a babel-esLint parser.

So, here we directly configure the standard and babel-esLint parser, plus some custom rules, and finally configure the following rules:

module.exports = {
  root: true.parserOptions: {
    parser: 'babel-eslint'.// Parse some of the latest ES syntax
    sourceType: 'module'  // The module is ECMAScript
  },

  extends: ['standard'].// Use standard

  rules: {
    'no-debugger': 'error'.// Disallow debugger in code
    quotes: ['error'.'single']./ / single quotation marks
    semi: ['error'.'always'] // The code needs to end with a semicolon}};Copy the code

After the ESlint specification file is configured, we can add the Prettier configuration file, create the.prettierrc.js file, and add the following:

module.exports = {
  printWidth: 800.// Single line width limit
  tabWidth: 2.// TAB uses two Spaces
  useTabs: false.// Instead of using TAB indentation, use space indentation
  semi: true.// Code needs to end with a semicolon
  singleQuote: true./ / single quotation marks
  bracketSpacing: true.// The left and right sides of the object need Spaces
  jsxBracketSameLine: false.// HTML closes the tag line feed
  arrowParens: 'avoid'.// Single-argument arrow function arguments do not require parentheses
  proseWrap: 'never'./ / reference https://prettier.io/docs/en/options.html#prose-wrap
  trailingComma: 'none' / / reference https://prettier.io/docs/en/options.html#trailing-commas
};
Copy the code

After the configuration is complete, we create a new file to test the effect. Create a new file named test.js in the SRC directory and fill in the following:

Use automatic formatting

As you can see, the file doesn’t conform to our ESLint specification, so we’ll try to fix it using ESLint formatting and prettier formatting respectively.

To start, type eslint –fix SRC /test.js on the command line and see what happens (as shown below)

As you can see, extra Spaces are removed, double quotes are replaced with double quotes, and Spaces are added to the left and right sides of the assignment operator.

Prettier -w SRC /test.js The file was restored and formatted using the command prettier -w SRC /test.js

As you can see, because esLint and Prettier used the same rules as prettier, the formatted files are highly similar.

In this way, we have completed the unification of the code specification format.

Vscode plug-in

As you can see from the above sample code, writing non-canonical code directly raises an error in the editor, because the above sample code is shown using vscode with plug-ins installed to aid development.

Let’s take a look at these plug-ins.

Let’s start by installing the ESLint plugin via vscode (see figure below).

After installing the ESLint plugin, the plugin reads the ESLint configuration file in the directory and checks for errors in the code (see figure below).

If we set the following property in vscode, the code will be automatically formatted when the file is saved. (As shown below)

Next, we can install the Prettier plug-in (see figure below).

After installing the plug-in, use the keyboard combination shift + Command/CTRL + P to invoke the Settings, and then type Format Selection With… Press Enter to select Prettier (as shown in the following figure).

After setting, use shift + Option/Alt + F to format the file.

These two plug-ins have more features that you can explore on your own.

A couple of things about plugins

If you are familiar with vscode plug-ins, you can skip this section.

During the installation of vscode plug-in, there have been many problems reported by children’s shoes. Here are some solutions to common problems.

Plugins don’t work

  1. Global installationnpm i eslint prettier -g
  2. installedvscodeAfter plug-in, restartvscode
  3. If that doesn’t work, upgradevscode

Plug-in not enabled

The new version of vscode requires you to manually enable the eslint plugin. Check the working status of eslint in the lower right corner. (As shown below)

It does not work after being enabled

Check the working status of ESLint in the lower right corner. Click to output logs. (As shown below)

According to the output log, repair, for example, the above is the lack of the corresponding plug-in, just install.

Saves are not fixed according to ESLint rules

This is probably because your vscode has save auto-formatting enabled. First go to preferences > Settings, search for format on save, and then turn this option off (as shown below).

The normal work

The working esLint and Prettier plugins are shown below.

Automatically detect and format code at commit time

Automatic formatting is not always a comfort during project development, as not all members of the project team use the vscode plug-in for automatic formatting.

This situation can lead to some non-standard code being submitted to the server, which can still cause the team specification to be inconsistent. In this case, automatic detection and formatting of the code at the time of submission is needed.

Next, we will use Husky for automatic detection of code submission.

First use NPM I husky -d to install the dependency. After the dependency is complete, we need to initialize husky with this command (as follows)

npx husky install && npx husky set .husky/pre-commit "npm run pre-commit"
Copy the code

Initialize git hook. Before git commit, run the pre-commit command.

So, we also need to add pre-commit to the project’s package.json, which will run esLint checks (see below).

"scripts": {
  "pre-commit": "eslint src"
}
Copy the code

Git add. And git commit -m ‘test’ to commit the code.

As shown in the figure above, the commit failed when the code was detected not complying with the ESLint specification.

If we want to automatically fix ESLint syntax errors while detecting errors, we need to have lint-staged installation using NPM I lint-staged -d and then modify the pre-commit command in package.json. Add the following.

"scripts": {
  "pre-commit": "lint-staged"
},
"lint-staged": {
  "src/**": [
    "eslint --fix"]}Copy the code

Next, run git add. And git commit -m ‘test’ again to try to commit the code.

As you can see from the figure above, after running Lint-staged commands, code that does not conform to specifications is automatically formatted correctly via ESLint –fix.

This completes the automatic detection and formatting of code when it is submitted.

Use scaffolding to automate the configuration

Manual configuration problems

Once you’ve configured the above, it seems like you’re done and ready to go down the happy road of normative coding, but it’s not.

A closer look reveals the tedious steps we need to take when we need to configure code specifications in a new project.

  1. Install Eslint.
  2. Install the corresponding ESLint rule configuration NPM package based on the project type.
  3. Install relevant plug-ins, parsers, and so on, depending on the project type.
  4. Configure the.eslintrc. prettierrc file based on the project type.
  5. Install code submission check + automatic formatting tool. husky + lint-staged
  6. Configuration package. Json.
  7. Test and fix problems.

These tedious steps can take a lot of time, and there may be some errors that need extra time to troubleshoot. Such a process may be a good learning opportunity for individuals, but it is an inefficient way for teams to collaborate.

So, to help with this, we can use a tool that generates a canonical configuration based on the configuration selection, and installs compatible dependencies.

Use scaffolding for automatic configuration

We used the NPM I standard-config-cli -g command to install the scaffolding tool globally, and then ran the JGXL standard command in the corresponding directory.

Using the vue + typescript command as an example, the configuration selected is shown below.

After the initialization, the corresponding configuration files are as follows:

.eslintrc.js

.prettierrc.js

package.json

As you can see from the above, our specification configuration generates the corresponding specification configuration file based on the selected configuration, and the dependency of the relevant version has been installed.

As a team member, you don’t need to care about the minutiae of these specifications and just do the core business development.

TIPS: The autofix feature only fixes some code style specifications. It does not automatically fix code problems that might cause problems (e.g., defined but unused variables).

summary

In the code style specification debate, everyone has their own interpretation and there is never a right answer. Instead of spending time arguing about details, focus on the core business.

And no matter how you argue, you always choose a style. Here, too, there is a trade-off between individual semantics and universal value.

So pick a front-end specification standard (like Standard) and stick with it. Save time for other meaningful problems! There comes (^ ^) /

References:

  • 10 Design Flaws with Javascript
  • eslint
  • standard
  • prettier
  • Use ESLint+Prettier to unify front-end code styles
  • ESLint application practices in medium and large teams (Meituan)
  • Why (and how) to use eslint in your project
  • Automate Your Coding Standard

One last thing

If you’ve already seen it, please give it a thumbs up

Your likes are the greatest encouragement to the author, and can also let more people see this article!

If you find this article helpful, please help to light up the star on Github.