Words: 7543; Reading Time: 20 minutes click to read the original article

The world engaged in, can not be unable to instrument. Nothing can be achieved without means. ——- Mozi’s Dharma Instrument

【 Front-end Engineering 】 Series of links:

  • 01 Set sail – development environment
  • 02 White Flawless – Package manager
  • Sweep the Eight Wasters -Webpack Basics
  • 04 Swept the Eight Wasteland -Webpack advanced
  • The future is here. -Babel

Sample code repository:Github.com/BWrong/dev-…

Declaration: If an error occurs following the code in this article, check whether the dependent version is consistent with the sample code repository.

As an ancient saying goes, “without rules, fangyuan can’t be built.” It seems that the concept of rules and fangyuan has been around for a long time. However, in a highly civilized modern society, legal rules are more perfect.

There are rules to everything, and so is programming, especially when multiple people are working together, and it’s important to follow good programming rules, so there are a lot of tools for code review. In this article we will only cover ESLint, which is also the most popular code review tool on the front end.

An overview of the

JavaScript is a dynamically weakly typed language that, while flexible to use, is prone to error. The Lint tool helps us spot problems caused by writing irregularities at development time.

Lint addresses the following issues:

  • Avoid some low-level errors, find out syntax errors, redundant code
  • Make sure the code follows the recommended style and unify the team’s code specifications

Evolutionary history

In the evolution of Lint tools (JS only), there have been three typical tools: JSLint, JSHint, and ESLint.

  • JSLint

JSLint was the first JavaScript Lint tool. It was developed by Douglas Crockford (author of “the Essence of JavaScript”) at a time when the front-end was still in its infancy and the Lint tool was very useful. However, like the authors themselves, JSLint has a very personal style and does not allow users to change rules. If they use it, they must follow all the rules.

  • JSHint

Since JSLint couldn’t change rules, many people couldn’t stand it, so JSHint came along, providing a rich set of configuration items that developers could customize to their own needs. And it was community-driven, so users grew quickly after it came out. Earlier jQuery also used JSHint for code checking.

  • ESLint

Back in 2013, Nicholas C. Zakas (author of JavaScript Advanced Programming) wanted to add a custom processing rule to JSHint while he was developing it, but it didn’t work. Inspired by PHP Linter, ESLint created its own Linter over a weekend in June of the same year. This is the bull man, a word against a wheel.

Unlike the first two tools, ESLint parses code using an AST and is highly extensible, so with the advent of things like ES6 and JSX, as long as there is a corresponding parser or plug-in, it can be quickly supported in a way that the other two tools can’t. So ESLint quickly became popular when ES6 came along, and Babel also provided it with a babel-ESLint parser to make ESLint even more popular.

In 2016, ESLint integrated JSCS, another Linter tool that was created around the same time (also in an AST-based manner), and ESLint has now taken its place on the JS Linter throne as an essential tool for front-end engineering.

In TypeScript’s early days, ESLint was used instead of ESLint. However, due to design issues, TSLint was officially abandoned in 2019 in favor of ESLint, which supports ESLint by providing parsers and plugins.

ESLint is undoubtedly a success, thanks to a good architectural design:

  1. Separation of concerns: The parser, core, and rules are all relatively independent, each doing its job, and have good maintainability and extensibility.
  2. Support for custom rules: You can customize rules and related events, giving developers more space to expand. To date, the community has many rule plug-ins, such aseslint-plugin-react.eslint-plugin-vueAnd so on.
  3. Keep the kernel as simple as possible: the kernel as simple as possible, through the way of plug-in function expansion, the core does not have any framework, library coupling, has a strong adaptability.

Zakas has also written an article on why ESLint succeeded.

Reference: Evolution of JS Linter

ESLint

ESLint is officially defined as a tool for finding and reporting problems in code, and for auto-fixing some problems. In addition to functions similar to JSLint and JSHint, ESLint has the following features:

  • ESLint uses Espree for JavaScript parsing.
  • ESLint uses the AST to evaluate patterns in code.
  • ESLint is fully pluggable, and each rule is a plug-in that can be added at run time.

With that said, let’s take a look at how to use ESLint.

use

The installation

You can install globally or locally. Local installation is recommended and will be used later.

#Global installation
npm install -g eslint
#Local installation of the project (recommended)
npm install -D eslint
Copy the code

After the installation is successful, execute the following commands in the project root directory to complete a series of Settings to create the configuration file.

npx eslint --init
Copy the code

Eslintrc.js file is created in the root directory of the project with the following contents:

module.exports = {
    'env': { // Environment Settings
        'browser': true.'es2021': true.'node': true
    },
    'extends': 'eslint:recommended'.// Use official or community preset rules
    'parserOptions': { // Parser configuration
        'ecmaVersion': 12.'sourceType': 'module'
    },
    'rules': {  // Custom rules
        'indent': [
            'error'.4].'linebreak-style': [
            'error'.'windows'].'quotes': [
            'error'.'single'].'semi': [
            'error'.'always']}};Copy the code

This is the configuration file for ESLint, of course there are many other ways to configure lint, which we’ll cover in detail in the configuration section later, but we’ll use this method for the time being.

How to use

ESLint is very flexible and can be used in a variety of scenarios, as we’ll see below.

The command line

Now create a file./ SRC /index.js:

// ./src/index.js
let test = 1
Copy the code

Then enter the command from the command line:

npx eslint ./src/index.js
Copy the code

As you can see, ESLint gives us two errors:

  • testA variable is defined but not used
  • let test = 1The semicolon is missing because it is always required in the configuration file above

This is the first function of ESLint: to find and warn of problems in code.

You don’t have to do things like add semicolons to your code yourself, ESLint has an auto-fix feature that can help you automatically fix simple problems.

Execute the command with the –fix argument:

npx eslint --fix ./src/index.js
Copy the code

/ SRC /index.js: / SRC /index.js:

// ./src/index.js
let test = 1; 
Copy the code

Does it automatically add a semicolon? oh~oh! That’s cool.

Note:

  1. ESLint doesn’t know how to fix the first problem above, so it doesn’t handle it. Instead, it throws an error or warning.
  2. When you run a command, you can specify multiple files by using wildcard characters, such asnpx eslint ./src/**You can check all files in the SRC directory.

Here we have introduced the most basic usage scenario of ESLint — the command-line mode. In addition to the above usage, there are a number of arguments that can be passed in.

  • -c.--config: Specifies the configuration file
  • --env: Specifies the execution environment
  • --global: Defines global variables
  • -h: View help

See the official documentation for more usage.

Webpack (eslint – loader)

Previously, we introduced how to use it in command line mode. When detection is needed, relevant commands must be executed in the command line. Is there any way to run it automatically when we start the project?

The answer is yes, webPack is the most popular build tool at the moment, and ESLint also provides esLint-Loader for it to do code checking and fixing at build time.

First you need to install eslint-Loader and ESLint:

npm install eslint-loader eslint --save-dev
Copy the code

Then add the corresponding configuration to the WebPack configuration:

// webpack.config.js
module.exports = {
  // ...
  module: {
    rules: [{test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader'.options: {
          // Here is the configuration for ESLint. Configuration files are recommended}},],},// ...
};
Copy the code

Note:

  1. Since ESLint checks for code written by us and not compiled by other Loaders, we have to be sureeslint-loaderExecutes first, so it should be placed at the end of the rule, and can also be usedenforce: 'pre'Set to force the setting to be executed before another loader.
  2. eslint-loaderThe configuration of esLint is recommended to be placed in the esLint configuration file, not in the Loader options.

After the above configuration, when the build command is executed, the check is performed first and the check result is printed on the terminal (only the check is performed and the build result is not affected).

However, when we generally code, the terminal is running in the background, viewing these information must be switched back and forth, it is very inconvenient. As a lazy cancer patient, certainly not want to. Those of you who have used vue-CLI know that if there is an error message, it will pop up in the browser.

In fact, the configuration is quite simple, do not understand their own back to the webpack section.

// webpack.config.js
module.exports = {
    // ...
 	devServer: {
        overlay: true  // The default value is false. Set it to true
    }
    // ...
}
Copy the code

Using (VSCode) in the editor

The use method introduced above is very convenient, but as a severe lazy cancer patient, I still found some problems in the use:

  • Problems in the code need to be discovered after compilation, not at the time of writing, so lack of timeliness, can it be reported as soon as it is written?
  • If it’s a simple formatting problem, can we do an automatic fix before saving without us having to worry about it?
  • Some of the older projects weren’t built using Webpack, so how do we get error messages when we’re coding?

Sure enough, laziness is productivity, and some of the big guys provide editors with ESLint plugins that solve the above problem perfectly.

Tip: the following is only used in VSCode, please check the use of other editors.

First install the ESLint plugin, CTRL +p in VSCode and type the following command:

ext install dbaeumer.vscode-eslint 
Copy the code

Now open up the previous code with VSCode and you can see that some of the code has a yellow (warning) or red (error) wavy line under it. If you mouse over it, you can also see the details of the error and how to fix it.

Instead of having to go to a terminal or a browser to check for error messages and then go to a file to find the code in question, we are now prompted immediately when we write code.

So, the second question is, can some simple formats be fixed automatically?

Just add the following configuration to VSCode configuration and some simple formatting problems will be fixed automatically when saving files.

"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
 }
Copy the code

Tip: VS code-esLint is supportedconfigurationOf, providedeslint.optionsTo set the global configuration, if there is no configuration in the project, will be the bottom of the configuration here.

"eslint.options": {
  "root": true."plugins": []."env": {},
  "extends": []."rules": {},
  "exclude": []
  "parserOptions": {}},Copy the code

For some projects, it doesn’t matter if you don’t use WebPack, you just need to install ESLint and add the corresponding configuration to the project and it will take effect at code time.

The ESLint plugin also provides a global way to install ESLint globally and put the ESLint rule configuration in VSCode’s ESLint plugin configuration to take effect for all open files.

If the project also has its own configuration, the configuration merge is performed. If the configuration items conflict, the configuration items in the project have priority and overwrite the global configuration.

Now that the common uses of ESLint are covered, let’s take a look at some of the core stuff.

configuration

ESLint provides a rich set of configuration items that allow users to configure their parser, environment, global, rules, and plug-ins according to their own needs.

These configuration items will be described in more detail later, but let’s see how to add configuration items first.

Configuration mode

ESLint supports several configurations, which can be summarized as follows:

  • Command line: When running the eslint command, configuration information is passed in through the configuration parameters provided by the CLI. This method is cumbersome and is generally not used.
#Some Common Configurations
#--env: Sets the environment
eslint --env browser,node file.js
eslint --env browser --env node file.js
#--global: Sets global variables
eslint --global require,exports:true file.js
eslint --global require --global exports:true
#--rule: Sets a rule
eslint --rule 'quotes: [2, double]'
eslint --rule 'guard-for-in: 2' --rule 'brace-style: [2, 1tbs]'
eslint --rule 'jquery/dollar-sign: 2'
#.
Copy the code
  • Inline comments: Annotate the configuration in a code file (usually at the top of the file). This is not often used because of the lack of reusability, and can be used if a file requires special configuration.
/* eslint-env browser, node */     // Set the environment
/* global var1, var2:writable */   // Set global variables
/* eslint eqeqeq: "off", curly: "error" */    // Set rules
Copy the code
  • The configuration file(Recommended) : Provided.eslintrc.*File or in thepackage.jsonIn theeslintConfigProperty.

Tip: Using a configuration file is the way I use it most often because it’s simple and intuitive, and the following is based on it. Other methods are similar, except for the format.

ESLint configuration files support multiple file formats: JS, CJS, YAMl, yML, and JSON. If multiple file formats exist in the current directory, ESLint will select only one of them in the following order:

  1. .eslintrc.js(recommend,eslint --initThe default generated configuration is this format.)
  2. .eslintrc.cjs
  3. .eslintrc.yaml
  4. .eslintrc.yml
  5. .eslintrc.json
  6. .eslintrc(waste)
  7. package.json

Since.eslintrc.js configuration is flexible and has high priority, this format is generally applicable to configuration files.

Configure the combination and priority

When configured using.eslintrc.* and package.json, the cascading composite behavior is triggered. Here’s how it works:

  • Use the nearest one first.eslintrc.*Configure, and then look for all configurations in all parent directories, and so on, until the root directory or a configuration is found"root":trueTo stop the search for the superior configuration file.
  • All configurations matched in the previous step are combined based on the search sequence (from inside to outside). Configuration items in the inner layer have higher priorities. If configuration items conflict after combination, configuration items with higher priorities (inside > Outside) are used.
  • If you have both in the same directory.eslintrc.*andpackage.jsonFile, will use the former configuration, the latter configuration will be ignored.
  • You can add it in the configuration"root":trueForce the directory to be root to prevent further lookups.

An: chestnut: :

Your -project ├─ package.json <- {"eslintConfig": {... }} ├ ─ ─. Eslintrc. Js ├ ─ ─ lib └ ─ ─ source. The js └ ─ ┬ test1 ├ ─ ─ the eslintrc. Js └ ─ ─ index. The js └ ─ ┬ test2 ├ ─ ─ the eslintrc. Js < - { "Root ": true} ├ ─ index.jsCopy the code

The directory structure above can be combined in the following ways:

The target Effective configuration combination
/lib/* /.eslintrc.js libIf no configuration file exists in the directory, the system searches for it/.eslintrc.jsand/package.json, but they are in the same directory, only/.eslintrc.jsTo take effect.
/test1/* /test1/.eslintrc.js+/.eslintrc.js test1After the configuration is found in the directory, go up and find the configuration/.eslintrc.jsand/package.json(ignore), will/test1/.eslintrc.jsand/.eslintrc.jscombination
/test2/* /test2/.eslintrc.js test2The directory exists and is configured"root":true, so it doesn’t look up, only/test2/.eslintrc.jsTo take effect

There are a number of configurations that ESLint supports, so it’s worth stating their priorities in descending order:

priority Configuration mode describe
1 Inline comment configuration /*eslint-disable*//*eslint-enable*/ /*global*/ /*eslint*/ /*eslint-env*/
2 Command line options --global --rule --env -c.--config
3 Project level configuration files .eslintrc.*orpackage.json

It is important to understand these combination rules and priorities so that they can be used wisely.

Configuration items

As mentioned earlier, ESLint configurations are for parsers, environments, globals, rules, and plugins, so let’s take a closer look.

Note: The following configurations are used.eslintrc.jsIf you need other ways, please explore by yourself.

The parser

By default, ESLint uses Espree as its parser, although we can specify other parsers as well.

// .eslintrc.js
module.exports = {
	parser: "esprima"
}
Copy the code

Here are some common parsers:

  • Esprima: An early parser adopted by ESLint, on which Espree was originally created.
  • @babel /eslint-parser: Makes Babel compatible with ESLint and supports some Babel syntax.
  • @typescript-eslint /parser: With the deprecation of TSLint, typescript provides this parser for ESTree compatibility to enable esLint to support typescript.

In addition to configuring parsers, you can provide options for configuring parsers:

// .eslintrc.js
module.exports = {
	"parser": "esprima"."parserOptions": {
        "ecmaVersion": 6.// Default 5: specifies the ECMAScript version. The year and version format are supported to support the new syntax of the ECMAScript version
        "sourceType": "module".// The default is 'script'. If ESModule is used, you need to set it to 'module', otherwise the import and export keywords will be error
        "ecmaFeatures": { 
            "jsx": true.// Enable JSX syntax
            "globalReturn": false.// Whether global return is allowed
            "impliedStrict": false  // Whether to enable strict mode. Only ecmaVersion greater than 5 is valid}}}Copy the code

The environment

Environment configuration is used to pre-define some global environment variables and syntax support for the corresponding environment. You can specify one or more environments.

// .eslintrc.js
module.exports = {
    "env": {
        "browser": true."node": true}}Copy the code

Common environments are as follows:

The environment describe
browser Add browser global variables, such aswindow
node Add node.js global variables and node.js scopes
es6,es2017,es2020,es2021. Add the version of the global variable and setparserOptions.ecmaVersionSet this parameter to the version number
amd addrequire()anddefine()The global variable
jquery addjQueryand$The global variable

See the official documentation for more environments.

Some plug-ins provide environments that can be used in the following format:

// .eslintrc.js
module.exports = {
    "plugins": ["example"]."env": {
        "example/custom": true}}Copy the code

The global variable

When using global variables that are not defined in the current file, ESLint will throw an error telling us that the variable is not defined, so you can manually add the variable to the global variable in the configuration file.

// .eslintrc.js
module.exports = {
    "globals": {
        "var1": "writable"."var2": "readonly"."var3": "off"}}Copy the code

Three configuration values are supported:

  • Writable: Allows variables to be overwritten by changes
  • Readonly: Sets the variable to read-only and not overwrite
  • Off: Disables the variable

The plug-in

ESLint provides a plugin mechanism that allows developers to customize validation logic, validation rules, or special syntax. Plugins can provide extension configurations, rules, environments, and so on. Plugins for ESLint start with eslint-plugin-, which needs to be omitted during configuration.

// .eslintrc.js
module.exports = {
    // ...
    "plugins": [
        "jquery".// eslint-plugin-jquery
        "@foo/foo".// @foo/eslint-plugin-foo
        "@bar"      // @bar/eslint-plugin]."extends": [  
        // Add plugin to plugins:
        "plugin:@foo/foo/recommended"."plugin:@bar/recommended"]."rules": {
        // Modify the rules in the plug-in
        "jquery/a-rule": "error"."@foo/foo/some-rule": "error"."@bar/another-rule": "error"
    },
    "env": {
        // Modify the environment in the plug-in
        "jquery/jquery": true."@foo/foo/env-foo": true."@bar/env-bar": true,}// ...
}
Copy the code

Some commonly used plug-ins:

The plug-in describe
eslint-plugin-react Support for React
eslint-plugin-vue Vue support, support.vuefile
eslint-plugin-prettier Prettier Supports formatting by ESLint
@typescript-eslint/eslint-plugin Provides support for TypeScript

Tip: If you want to develop your own plugins, you can use the official templates provided by ESLintgenerator-eslintDevelopment.

The rules

ESLint provides a number of rules that can be finely controlled.

The configuration format is as follows:

// .eslintrc.js
module.exports = {
    "rules": {
        "eqeqeq": "off"."curly": "error"."quotes": ["error"."double"]}}Copy the code

The preceding configuration values can also be in the form of numerical values. The mapping is as follows:

Configuration values describe
offor0 Disable detection for this rule
warnor1 Enable the detection of change rules and throw them if they are not metwarning
erroror2 Enable the detection of change rules and throw them if they are not meterror

Configuration rules If there are configuration items, you can write the values in array format. The first element is the configured value, and the second element is the configuration item.

The extension configuration

ESLint provides so many rules that you can’t configure them from scratch every time! So ESLint provides the extends configuration, which we can extend based on some mature configuration or override its rules:

// .eslintrc.js
module.exports = {
    "plugins": [
        "react"]."extends": [
        "eslint:recommended"."plugin:react/recommended" // Extend the configuration in the plug-in]."rules": {
       "react/no-set-state": "off"  // Override rule}}Copy the code

There are many configuration sets available for us to extend. Here are some common ones:

configuration describe
eslint:recommended ESLint is built in to enable some recommended core validation rules
eslint:all ESLint is built in to enable all core validation rules
eslint-config-airbnb Check according to Airbnb style rules
eslint-config-standard Perform verification according to standard style rules
eslint-config-prettier Example Disabling Prettier conflicts rules

In addition to using configurations provided by the community, teams can also customize their own set of configurations and publish them to NPM so that the team can share the configurations. Published packages must be named starting with eslint-config-, such as eslint-config-myconfig, and it is recommended that the keyword be eslintconfig so that others can find it. The contents of the package are similar to.eslintrc.js:

// eslint-config-myconfig/index.js
module.exports = {

    globals: {
        MyGlobal: true
    },

    rules: {
        semi: [2."always"]}};Copy the code

Disable and ignore

ESLint is great, but there are situations where we just want to be quiet and not get caught up in too many “worldly” rules. In particular, it’s a good idea to disable or ignore some rules and files, especially if you have ancient code and have ESLint validation enabled, which might lead you to suspect that your occurrence is an error: broken_HEART :: BROKEN_heart :: Broken_heart :: Broken_heart :: Broken_heart:.

You can disable a rule in the following ways:

// 1. Place it at the top of the file and disable all rules when checking the file
/* eslint-disable */  
alert('foo');

// 2. Disable the specified rule when checking this file
/* eslint-disable no-alert, no-console */  
alert('foo');
console.log('bar');

// 3. Disable all rules when detecting this line
alert('foo'); // eslint-disable-line 
alert('foo'); /* eslint-disable-line */

// 4. Disallow all rules when checking the next row
// eslint-disable-next-line
alert('foo');
/* eslint-disable-next-line */
alert('foo');

// 5. Do not specify a rule when checking this line
alert('foo'); // eslint-disable-line no-alert, quotes, semi
alert('foo'); /* eslint-disable-line no-alert, quotes, semi */

// 6. Disallow specifying rules when testing the next row
// eslint-disable-next-line no-alert, quotes, semi
alert('foo');
/* eslint-disable-next-line no-alert, quotes, semi */
alert('foo');
Copy the code

In addition to the above configuration in files, you can also configure to disable verification rules for a group of files:

// .eslintrc.js
module.exports = {
  "rules": {... },"overrides": [{"files": ["*-test.js"."*.spec.js"]."rules": {
        "no-unused-expressions": "off"}}}]Copy the code

ESLint also provides a file. Eslintignore is used to ignore verification of files, where directories configured are ignored by ESLint.

/build/
/config/
/dist/
/*.js
Copy the code

In some cases

Now that we’ve seen how ESLint can be used, let’s take a look at some common use cases:

ESLint +TypeScript

To support TypeScript, you need to configure the @typescript-esLint /parser parser to support the TS special syntax and install the @typescript-eslint/eslint-plugin to provide validation rules.

  1. Installing dependency packages
npm install @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint typescript --save-dev
Copy the code
  1. Configure the parser. For more parser configurations see [this document nginx.conf](github.com/typescript-…).
// .eslintrc.js
module.exports = {
  "parser""@typescript-eslint/parser".// Configure the parser
  "parserOptions": {
      "ecmaFeatures": { 
        "jsx"true  // If JSX is used, it needs to be enabled
      },
      "project""./tsconfig.json".// ts configuration file
      / /... More configuration}}Copy the code
  1. Configure plug-ins and rules
// .eslintrc.js
module.exports = {
  "parser": "@typescript-eslint/parser"."plugins": ["@typescript-eslint"].// Configure the plug-in
  "extends": ["plugin:@typescript-eslint/recommended"] // Extends the rules recommended by typescript-esLint
  "rules": {
      "@typescript-eslint/indent": ["error".2].// Override plug-in verification rule configuration
  }
  // ...
}
Copy the code

See the typescript-ESLint documentation for more uses of typescript-ESLint.

ESLint + Prettier

Prettier

Prettier before I start, it’s important to know a little about Prettier.

Prettier is an “independent” code formatting tool that supports JSX, Vue(Where Prettier is used in Vetur), TypeScript, Less, Sass, JSON, GraphQL, and almost every file format used by the front end. And it can be used in a variety of scenarios, is the most popular formatting tool.

Let’s look at one of the most common ways to use it as an editor plug-in:

  1. Prettier-code Formatter install the VSCode plugin prettier-code Formatter
ext install esbenp.prettier-vscode
Copy the code

  1. Install the Prettier
NPM install -g prettier # NPM install -d prettier #Copy the code
  1. Adding configuration to a project, Prettier also supports multiple formatsThe configuration fileHere we useprettier.config.js
module.exports = {
  printWidth: 80.// Length per line (default 80)
  tabWidth: 2.// How many Spaces per TAB (default: 2)
  useTabs: false.// Indent with TAB (default false)
  semi: true.// End with a semicolon (default true)
  singleQuote: false.// Use single quotes (default false)
  trailingComma: 'none'.// Use trailing comma (default none)
  bracketSpacing: true.// Use Spaces between object braces (default true)
  jsxBracketSameLine: false.// The > in multi-line JSX is placed at the end of the last line, not on a new line (default false)
  arrowParens: "avoid" // Avoid parentheses when arrow functions have only one argument (default: avoid)
};
Copy the code

Tip: Check out more configuration itemsPrettier-Options.

When VSCode does the formatting, select Prettier to format as we configured it. This avoids the problem of different styles of formatted code due to different editor configurations.

So what does this have to do with ESLint? Why are they having an affair?

ESLint conflicts with Prettier

While Prettier formats code as often as possible, Prettier formats code according to configuration, where configuration is not universal and some configuration rules conflict. So when code is formatted with Prettier, ESLint thinks there is something wrong and throws an error.

To solve this problem, eslint-plugin-prettier and eslint-config-prettier are used:

  • ‘eslint-plugin-prettier: To set the rule for prettier into an ESLint rule.

  • Eslint-config-prettier: Disables a rule in ESLint that conflicts with Prettier.

npm install -D eslint-plugin-prettier eslint-config-prettier
Copy the code
// .eslintrc.js
module.exports = {
    extends: [
        'plugin:prettier/recommended' Extends: ["prettier"],plugins: ["prettier"]
      	// 'prettier/@typescript-eslint' // if typescript, add this to @typescript-eslint and prettier].rules: {
        "prettier/prettier": [  // Overwrite, customize prettier rule
          "error",
          {
            "singleQuote": true."trailingComma": "none"."bracketSpacing": true."jsxBracketSameLine": true}}}]Copy the code

ESLint and Prettier now Prettier and ESLint could be happy together :tada:: Tada :: Tada ::

engineering

Before we saw ESLint and Prettier, tools that regulate the code we write work only at development time and don’t guarantee that the code we put into the repository will conform to the specification.

For example, a new employee in the department found these restrictions troublesome, so he disabled these tools and directly submitted the code to the warehouse after development. So we need to make some restrictions, the submission of non-standard code is prohibited, to improve the quality of the code in the library.

This can be done using Git hooks and husky & Lint-staged.

  • huskyB: It can be very convenientpackage.jsonGit hooks are defined
  • Lint-staged: Only some Linter actions are used for Git submitted code (not all),
#Install the husky lint - staged
npm i -D lint-staged husky
Copy the code
// package.json
"lint-staged": {
  "**/**.{js,json,pcss,md,vue}": [
    "prettier --write".// Perform formatting first
    "eslint --fix"."git add"]},"husky": {
  "hooks": {
    "pre-commit": "lint-staged"}},Copy the code

When this is set up, the code is checked every time a commit is made, and only if it passes the check can commit.

Note: Since these operations are local, it is still possible to skip the check by some means. If you have CI/CD, you can do it remotely to avoid skipping the check.

How to improve front-end application quality, Enterprise code specification and Static inspection

conclusion

That concludes the introduction to ESLint. If you want to learn more about ESLint, check out the discussion of how ESLint works.

No matter in writing code or doing other things, in fact, should use a long-term view, just use when there may be a lot of problems, it is also very time-consuming and laborious to change, but as long as you stick to it, the code quality and development efficiency will be improved, the early pay is worth it.

These tools are not necessary, you can develop features without them, but you can write higher-quality code with these tools. People who are new to these tools, in particular, may find it a hassle and give up, missing a great opportunity to improve their code.