preface
There are a thousand Hamlets in a thousand people’s eyes.
For a thousand programmers, there are a thousand code styles. In front-end development, there are several code style differences that are still being debated:
- Single or double quotation marks?
- Do I need a semicolon at the end of a line?
- Two Spaces or four Spaces?
- .
These code style differences are often teased and even intolerable in collaborative development.
In addition, due to the flexibility of JavaScript, there can often be multiple ways to write a single piece of code, which can lead to collaborative time differences. Also, there are some scripts that can lead to bugs that aren’t easy to find, or that don’t perform well and should be avoided during development.
To solve this type of static code problem, each team needs a common JavaScript code specification that team members follow to write code. Of course, relying on people to guarantee code specifications is not reliable, so you need a tool to do so, and ESLint is one of those tools.
Prettier also makes code look the same, some readers might say. Yes, Prettier does format code uniformly according to the rules she sets, as she will in a future article. But to be clear, Prettier only formats code, and ESLint can find hidden code quality problems that Prettier cannot find.
About ESLint
About ESLint, its Slogan is Find and Fix problems in your JavaScript code. As mentioned above, it can find and fix problems in your JavaScript code. ESLint has three features described on its website:
- Find the Problems. ESLint uses static code analysis to quickly find problems in code. ESLint runs in most text editors, and you can also plug ESLint into your workflow
- Fix Automatically. Many problems found by ESLint can be fixed automatically
- Customize. ESLint checking rules can be customized
Based on the above description, we can use ESLint in front-end engineering as follows:
- Create a unified set of ESLint code rules based on existing INDUSTRY ESLint specifications and team code practices
- Package unified code rules into ESLint rule packages for access
- Plug ESLint into scaffolding, editors, and development workflows
Quick learning
Here’s a quick introduction to using ESLint, but you can skip this section if you’re already familiar with it.
Create a new directory containing package.json (NPM init -y can be executed in an empty directory) and create a new index.js:
// index.js
const name = 'axuebin'
Copy the code
Install eslint:
npm install eslint --save-dev
Copy the code
Then execute./node_modules/.bin/eslint –init or NPX eslint –init to generate an esLint configuration file.eslintc.js:
module.exports = {
env: {
es2021: true,},extends: 'eslint:recommended'.parserOptions: {
ecmaVersion: 12,},rules: {}};Copy the code
Once the configuration file is generated, you can execute it./node_modules/.bin/eslint index.js
ornpx eslint index.js
Command to check the file. The results are as follows: index.js
The code inno-unused-vars
This rule, by default, this rule will reporterror
That is, ESLintDo not allow unused variables in code. This is a good habit for maintaining code.
Simple configuration
Let’s try configuring ESLint’s checking rules. Using semicolons and quotes, for example, now that you are the designee of your team’s code specification, you want your team members to develop code that is in single quotes and semicolons.
Open the.eslintrc.js configuration file and add the relevant configuration items to rules:
module.exports = {
env: {
es2021: true,},extends: 'eslint:recommended'.parserOptions: {
ecmaVersion: 12,},rules: {
semi: ['error'.'always'].quotes: ['error'.'single'],}};Copy the code
Then we change the code in index.js to:
// index.js
const name = "axuebin"
Copy the code
performeslint
After command:You can see the check result as follows:
- **[no-unused-vars] **’name’ is assigned a value but never used. The name variable is defined but not used.
- ** quotes **Strings must use singlequote. Strings must use single quotes.
- (semi) * * * * Missing semicolon. Missing semicolon.
Honestly modify the code as specified, using single quotes and enclosing semicolons. Of course, if you want double quotes and no semicolons, modify the configuration accordingly.
For details about how to configure each rule, see eslint.org/docs/rules
Auto repair
performeslint xxx --fix
Problems in some code can be fixed automatically, exposing problems that cannot be fixed automatically. For example, the quotation marks and semicolons mentioned above can be passed--fix
Automatic repair, whileno-unused-vars
ESLint cannot automatically fix unused variables.
Using configuration packs
In the configuration file generated by init, we see this line of code included:
module.exports = {
extends: "eslint:recommended"
}
Copy the code
This line of code means to use the recommended configuration of ESLint. Extends: ‘XXX’ extends. The current configuration extends from the configuration of XXX.
Therefore, we can also use any encapsulated configuration, which we refer to as a “configuration set” in this article, by searching eslint-config on NPM or GItHub. Common configuration packages are as follows:
- Eslint-config-airbnb: Configuration set provided by Airbnb, Inc
- Eslint-config-prettier: Shuts down rules that would conflict with Prettier
- Eslint-config-react: create the configuration set used by the React app
- Eslint-config-vue: configuration set used by vuejs
- .
Best practices
After a brief introduction to ESLint, more details on how to use ESLint and how to use it will not be covered in this article, but can be found on the official website. This article will focus on implementing ESLint in a team engineered architecture, and here are a few best practices.
Abstract configuration set
For independent developers and small teams with simple business scenarios, it is very efficient to use an off-the-shelf, complete set of third-party configurations that provide low-cost access to ESLint code checking.
However, for medium to large teams, when the actual code specification is implemented, it is not possible to have a tripartite configuration package that fully conforms to the team’s style, and we will manually add custom rules to the Rules configuration based on the extends tripartite configuration set. After A long time, the rules of APPLICATION A and application B may be different, and it is difficult to achieve the purpose of unification.
In this case, you need a centralized way to manage configuration packages: publish a configuration set based on the team’s code style (or based on an existing three-party configuration set), and the team can use the package centrally to manage and update it.
In addition, the current scenario for a front-end team can be complex from a technical perspective. Such as:
- The technology selection is inconsistent: React is used for PC and Vue is used for H5. Whether to use TypeScript
- There are many cross-terminal scenarios: Web and applets, as well as Node
- .
All of the above problems exist in real development, so when the code specification engineering solution is landed, a single function configuration set is not enough, this time also need to consider how the configuration set abstraction.
In order to solve the above problems, here is a solution idea:Specifically, there is a basic rule set similar to ESlint-config-Standard (including code style, variable correlation, ES6 syntax, etc.), and some plug-ins of the community (Vue/React) are integrated on this basis and packaged into a unified NPM Package for release. Consumption extends the corresponding configuration set through different paths depending on the current application type.
Here’s a Demo for those interested: eslint-config-axuebin
Developing a plug-in
ESLint provides a rich configuration for developers to choose from, but these generic rules are not sufficient in complex business scenarios and specific technology stacks. ESLint provides extensibility in the form of plugins that allow developers to customize arbitrary checking rules. For example, eslint-plugin-vue/eslint-plugin-react is an extension used in the Vue/react framework. The website also provides documentation to guide developers in developing a plug-in.
In general, we don’t need to develop plug-ins either, but we need to at least understand that there is one. The ESLint plugin can help us do some team code quality checks where we may have some special business logic.
Here I will not expand, mainly is some AST usage, according to the official documentation can be used, or you can refer to some existing plug-in writing method.
Scaffolding/CLI tools
Once we have the team’s unified ESLint configuration set and plug-ins, we integrate them into scaffolding for new project integration and out of the box. But for some old projects, if you need to manually modify or there will be some trouble, this time you can use the CLI to complete the one-click upgrade.
This article uses the Demo eslint-config-axuebin above to design a simple CLI Demo. Since the current configuration is also relatively simple, the CLI only needs to do a few simple things:
- Ask the user the type of the current project (JavaScript or TypeScript, React or Vue)
- Write according to the project type
.eslintrc.js
file - Install required dependencies based on the project type (e.g. Eslint-plugin-vue for vue)
- in
package.json
的scripts
writes"lint": "eslint src test --fix"
The core code is as follows:
const path = require('path');
const fs = require('fs');
const chalk = require('chalk');
const spawn = require('cross-spawn');
const { askForLanguage, askForFrame } = require('./ask');
const { eslintrcConfig, needDeps } = require('./config');
module.exports = async() = > {const language = await askForLanguage();
const frame = await askForFrame();
let type = language;
if (frame) {
type += ` /${frame}`;
}
fs.writeFileSync(
path.join(process.cwd(), '.eslintrc.js'),
`// Documentation\n// https://github.com/axuebin/eslint-config-axuebin\nmodule.exports = The ${JSON.stringify(
eslintrcConfig(type),
null.2
)}`
);
const deps = needDeps.javascript;
if (language === 'typescript') {
deps.concat(needDeps.typescript);
}
if (frame) {
deps.concat(needDeps[frame]);
}
spawn.sync('npm'['install'. deps,'--save'] and {stdio: 'inherit' });
};
Copy the code
The CLI Demo code can be run as follows:axb-lint, execute under project directory:axblint eslint
As shown in the picture:
automation
After configuring ESLint, we need to make developers aware of ESLint’s constraints. Developers can run the ESLint command themselves to run code checks, which is not efficient, so we need some automation to do this. Of course, at development time, the editor also provides the ability to check the file being edited against the ESLint configuration file in the current workspace, which is not our main concern.
There are several ways to do ESLint checks:
- Development time: Rely on the power of the editor
- Manual run: Manually execute the eslint command on a terminal
- Pre-commit: Automatically execute eslint before committing git
- Ci: Depending on Git’s continuous integration, you can upload check result output files to the server
As a pre-commit, ESLint checks every time local development is done before committing code to ensure that the cloud code is consistent.
This approach is simple enough to rely on Husky and Lint-staged projects. Once the dependencies are installed, add the following configuration to the package.json file:
{
"lint-staged": {
"*.{js,jsx,ts,tsx}": "eslint --cache --fix"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"}}}Copy the code
The effect is as follows:If your code runs ESLint to check for an Error, the commit process is interrupted:This ensures that the code submitted to the GitHub repository is uniform. (Of course, if you want to delete all the configuration files, you can’t help it.)
conclusion
This article introduces some ideas for ESLint best practices for small and medium front-end teams that you can build on to develop a complete ESLint workflow and implement it into your own team.
This article is the front-end code standard series of one of the article, several articles about StyleLint/CommitLint/Prettier, and there is a complete articles about front-end code standard engineering practice, stay tuned (possibly with the pigeons).
For more original articles, please follow the public account “Programmer playing with camera”, or add me on wechat XB9207 to communicate