1. Standardization introduction

Standardization is an important part of our practice of front-end engineering. Here, standardization is introduced from the following aspects:

  • Why should there be a standard

    • Software development requires collaboration of many people

    As the saying goes, “no rules, no standards” is the same for people to do things, especially in the development industry, it is necessary to have a rigorous working attitude -> in most cases, software development is not a single person’s work, it is required to cooperate with many people

    • Different developers have different coding habits and preferences
    • Different preferences increase project maintenance costs
    • Each project or team needs to have clear and consistent standards

    Get the project or team members to work to the same standards -> avoid the hassle of disagreements

  • Where do you need a standard during development

    • Code, documentation, even the commit log

    • An artificially written success during development

    • Code standardization is of Paramount importance

      Code specification largely determines the quality of the project and also determines the maintainability of the project -> in order to facilitate the later maintenance and team members to read generally, the code style will be uniform requirements -> here generally include:

      • Unify Spaces around keywords and operators
      • Uniform code indentation
      • Specifies whether to end with a semicolon
      • Uniform naming conventions for variables or functions
  • Methods of implementing standardization

    • Coding predecessors are standard conventions

      The initial implementation of the standardized operation is very simple. It only needs to agree a standard that can be implemented in advance -> then carry out their development work according to the standard -> finally, in the code-review process, the corresponding standard will be checked according to the agreed standard

      => However, there will be many problems in the implementation of standardization only by means of artificial agreement:

      • Artificial constraints are unreliable
      • It’s also hard for developers to remember every rule
    • Lint is implemented by tools

      Through the special tools to ensure the implementation of standardization relative to human inspection -> tool inspection is more rigorous and more reliable -> at the same time can also cooperate with automated tools to achieve automated inspection -> this standardization is easier to get quality assurance

      => Normally we use tools to find irregularities in a project and this process is called Lint -> The reason why Lint is called is: In the early days of C, there were some common code problems that the compiler couldn’t catch -> someone developed a tool called Lint to check for these problems before they were compiled so that they wouldn’t cause unnecessary problems later -> All subsequent tools like this were called Lint or “Lint” Linter -> Ex: the most common front-end ESLint, StyleLint, and so on

  • Common normalization implementation

    • ESLint tool
    • Customize the ESLint validation specification
    • ESLint support for TypeScript
    • ESLint combines automation tools or Webpack
    • A derivative of ESLint
    • Use of the StyleLint tool
    • Git Hock/ESLint/Git Hock/ESLint/Git Hock

2. ESLint is introduced

It’s now much more efficient to use tools to validate projects -> here’s ESLint:

  • The most mainstream JS Lint tools specialize in checking JS code quality

  • ESLint makes it easy to unify developer coding styles

    Ex: use of indentation, newlines, semicolons, and whitespaces -> ESLint can also help you find irregularities in code. Ex: defining variables that are not used, declaring variables after they are used, always choosing double equal (==) symbols when comparing, etc

  • ESLint can help developers improve their coding capabilities

    If you write code that finds a bunch of problems every time you do Lint -> most of these problems are bad coding habits -> over time you’ll remember the problems and avoid them the next time you code -> over time your coding ability will naturally improve

3. ESLint installation

Here is some work before ESLint uses -> ESLint installation and validation

ESLint installation steps:

  • Initialize the project

  • Install ESLint modules as development dependencies

    ESLint is a node-based NPM module -> install the ESLint module via NPM or YARN

  • Verify the installation by running CLI commands

    After the installation is complete, you can run simple commands to check whether the installation is successful

Initialize package.json from the command line

yarn init --yes
Copy the code

Install the ESLint module from the command line

cnpm i eslint -D
Copy the code

As for the present stage Seldom global installing a module – > because most cases are dependent on specific projects a module – > install the module in local let it together with the project management will be more reasonable – > and others to your project after don’t need to separate care project depends on what the global module directly through the NPM Install allows you to install the necessary tool modules -> this also improves the maintainability of the project from the side => Since the ESLint module provides a CLI program, there will be an extra ESLint executable on the node_modules/.bin project after installation The CLI program can then be used to detect problems in the code

View the version of ESLint from the command line

Yarn eslint-version or NPX eslint --versionCopy the code

Print out the version of ESLint -> There is no need to decide whether to use NPM or yarn -> There is no absolute difference between the two. Each has its own advantages. Use either version according to your team/project’s specific requirements

4. Get started quickly with ESLint

First complete project initialization and ESLint module installation; ESLint check steps:

  • Write the “problem” code

  • Use ESLint to perform code detection

  • Complete the ESLint use configuration

    ESlint must be configured for the first time before it can be used properly

Complete project initialization and ESLint installation

Create a new prepare.js in the project root directory and edit prepare.js

const foo = 123


function fn () {
  console.log('hello')
  
  	console.log('eslint')
  
  
}


fn(
  
  syy()
Copy the code

Run ESLint from the command line to find the problem in the above code

Follow ESLint orders need to take specific file path – > here path can also be a wildcard Because it can realize batch check – > choose here is that the specific path to the file

yarn eslint ./prepare.js
Copy the code

Run the following command: The terminal displays an error message:

Run esLint –init with an error message

yarn eslint --init
Copy the code

The console prints out deliverable issues:

  • Syntax error: well understood Ex: the call to the fn() method in the above code
  • Ex: This code defines an unused variable foo or calls a function syy that does not exist
  • Code style: It is best to understand that the initial expectation of ESLint is that ESLint will be able to find problems with coding style Ex: indented and newlines in code are inconsistent

Select To check syntax, find Problem, and enforce code style here

Q2: What type of modularity is used in your project?

The options here determine whether your code will allow the specified syntax or calls -> allow global require and exports functions if you select CommonJs -> use import() and export syntax if you select ESM -> None of these is not used in this code

=> Q3: Which framework is being used?

None of these

=> Q4: Do you use TypeScript in your code?

This one doesn’t use the input N

=> Q5: What environment will your code run in?

I’m gonna go ahead and select Browser

=> Q6: How do you want to define the project code style?

In general, choose: mainstream code style on the market -> so that if new members join the project can better and faster adapt to our style

=> Q7: Which is the mainstream style in the market?

After the selection -> three mainstream styles are given

Among them, Airbnb and Google are the specific coding norms of these two companies respectively -> and Standard is a set of norms in the community -> Individuals usually like standard specification: the biggest characteristics: You don’t have to put a semicolon at the end of the statement -> Standard and what you choose is up to you, right

=> Q8: What format do you want your configuration files to be stored in?

I recommend using the JavaScript format -> add some criteria in the configuration file to determine whether to enable certain functions

After selecting, the terminal prompts you to install additional plug-ins -> select Y -> NPM to install these plug-ins

Eslintc.js -> Run ESLint to verify prepare.js from the command line

yarn eslint ./prepare.js
Copy the code

After execution: The terminal detects an error

=> The first thing found here is a syntax error -> modify the fn() function call in prepare.js

Perform the ESLint check again from the command line

This time the terminal will find more errors: why didn’t these errors be detected just now -> The reason is: ESLint will not be able to check the code or style when there is a syntax error in code -> in this case, you can use the –fix parameter to auto-correct most code style problems -> this is done by –fix

The code style is fixed with the command line argument –fix

yarn eslint ./prepare.js --fix
Copy the code

After execution: the style of the code is automatically fixed -> But you have not developed good coding habits, I suggest you manually change the error messages at the beginning to impress you => here the console also prints out two problems:

=> Modify prepare.js: remove the definition of foo and the call to syy()

Running ESLint again -> does not report an error

** Basic functions of ESLint: 1. You can find problems in code -> Problems include syntax errors, code irregularities, and style inconsistencies. 2. ESLint can fix most problems with code style **

5. ESLint configuration file parsing

Here’s an in-depth look at ESLint configuration files: before Through the command eslint – init created under the root directory of the project. The slintRC. Js configuration file In this file to write configuration will affect the current directory and all subdirectories file – > under normal circumstances Is not going to manually modify the configuration file If you need to enable or disable certain verification rules and modify the configuration items in the configuration file => Next: Check the configuration contents in the configuration file

Do project initialization and ESLint initialization ahead of time

Create configuration.js in the root directory

Sample code will be written in it to show the results of the configuration file changes

Open configuration file

Since the configuration file ends up running in the Node environment, you can see that a configuration object is exported in CommonJs mode. There are four configuration options in this configuration object: 1. env 2. extends 3. parserOptions 4. rules

5.1. ESLint configuration item -env: Flags the environment in which the current code is run

We all know that JS has different apis that can be called in different runtime environments, and many of these apis provide an Ex for handling as a global member: In the browser environment, you can use the window and document objects directly. In the node environment, these objects do not exist => env: ESLInt determines if a member is available based on the current configuration environment -> to avoid using non-available members in code -> Ex: The browser in the current configuration: True means that the current code will run in the browser environment -> then you can use global objects such as document or window directly in the environment -> Each environment has a set of predefined global variables that are allowed to be used once the environment is turned on

Edit the configuration file to change the browser value to false

//.eslintrc.js
env: {
  browser: false.es2020: true},...Copy the code

Edit the configuration. Js

document.getElementById("#abc")
Copy the code

Run ESLint from the command line to check configuration.js

yarn eslint ./configuration.js
Copy the code

You can see: There is no report document undefined error – > at this moment because when generating ESLint configuration choice standard style The final configuration is also inherited the standard configuration – > in the standard configuration made some specific configuration At this moment The document and the window is can be used in any environment = > standard configuration can be found in the configuration file is to prove – > because extends the rules of the load is to look for eslint – config – standard file name – > Find eslint-config-standard under node_modules: this module exports the configuration of a JSON file. Find and open eslintrc.json

This file sets document, Navigator, and Window to global-read-only members via globals, and the current project configuration inherits from this file, so the previous env setting does not affect the use of document -> For this reason, you can use a global member in the window

Use alert in configuration.js

//document.getElementById("#abc")
alert(11)
Copy the code

Run ESLint checks on the command line

yarn eslint ./configuration.js
Copy the code

Running the code will tell the terminal that the alert is not defined

=> This proves that the env option is based on the configured environment information to determine whether the global member is available. => Which environments can be configured for env?

You can enable multiple environments at the same time. Ex: Set Browser and Node to true so that the global members used in both environments can be used at the same time

5.2. ESLint configuration item-extends: Extends some shared configuration

Extends: extends extends extends some shared configuration Ex: Most of the time, if you want to share an ESLint configuration between multiple projects -> you can define a common configuration file or configuration module and then extend that configuration or file in extends => The property value can be an array -> It can inherit multiple shared configurations at the same time which will be used later

5.3. ESLint Configuration Item-parserOptions: Sets the configuration of the syntax parser

ECMAScript has released a number of syntaxes in recent years. The keyword Ex: let const -> controls whether a particular version of the ES syntax is allowed

Edit the eslintrc. Js

. .parserOptions: {
  ecmaVersion: 5},...Copy the code

After the changes, there is no way to use the new ES6 features in your code

Edit the configuration. Js

const csa = 222
Copy the code

Run ESLint to check code from the command line

yarn eslint ./configuration.js
Copy the code

The console prints an error message:

If the ecmaVersion is lower than 2015, the sourceType cannot be module -> because ESModules are a new feature in ES2015, whereas in standard configuration the sourceType is set to module

Modify standard configuration file eslintrc.json: set sourceType to script

. ."sourceType": "script".Copy the code

Run esLint again to check the code: Error message ->

It is also important to note that the version configuration in parserOptions only affects the syntax check and does not mean that certain members are available -> if the global member Ex: Promise is provided by ES2015, it is still controlled by the ES2016 option in env

Modify. Eslintrc. Js

module.exports = {
  env: {
    browser: false.es6: false},... .parserOptions: {
  	ecmaVersion: 2015},... }Copy the code

Edit the configuration. Js

const foo = 1
let csa = 2
let a = new Promise(a)Copy the code

Run ESLint to check configuration.js(yarn eslint./configuration.js) -> console error: Promise is not defined=> Whether a specific member is available needs to be defined by the environment

5.4. ESLint configuration item-rules: Configures each validation rule in ESLint to be on or off

ESLInt configuration item: rules -> Enable/disable for each check rule -> Enable/disable for each check rule by turning on a property in rules. Property name built-in rule name property values can be three:

  • Off: Disables the rule
  • Warn: sends a warning
  • Error: An error is reported

Edit the eslintrc. Js

. .relues: {
  'no-alert': 'error'
}
Copy the code

Edit the configuration. Js

alert('cs')
Copy the code

Run the ESLint command to check configuration.js(yarn ESLint./configuration.js) -> Error ‘alert’ is not defined

=> What rules can be used specifically? -> ESLint provides a list of all the built-in validation rules available on the ESLint website -> The standard currently in use has a number of validation rules enabled that basically meet the validation requirements. If needed, you can configure them according to your own needs by modifying the configuration items in rules

5.5. ESLint configuration item – globals

This option is used to declare an additional global member Ex that can be used in code: You can add a new JQuery object with a value of readonly -> so that your code can use JQuery -> directly without any error

Edit the eslintrc. Js

. .globals: {
  "jQuery": "readonly"
}
Copy the code

Edit the configuration. Js

. jQuery('#cas')
Copy the code

Running ESLint to verify configuration.js -> does not prompt JQuery use error -> this is what globals does

6. ESLint configuration comments

Configuration comments can be interpreted as commenting the configuration directly in a script file -> then performing code validation -> why do you do this? One or two rule violations are inevitable when using ESLint during actual development — you can’t override a validation rule configuration because of one or two points in your project — > So in that case you can use ESLint’s configuration comments to resolve the issue => Do some preparation: Json, install the ESLint module, create eslint-configuration-comments.js in the root directory, and create the ESLint configuration file:.eslintrc.js in the root directory

Edit eslint – configuration – comments. Js

// Define a normal string in which business needs to use the ${} literal placeholder, but standard style does not allow this
const str1 = "${name} is a coder"

console.log(str1)
Copy the code

Run ESLint to check eslint-configuration-comments.js

yarn eslint ./eslint-configuration-comments.js
Copy the code

Running command console error:

You can use comments to temporarily disable the current rule. The syntax for these comments can be described in the official ESLint documentation

Edit eslint – configuration – comments. Js

In this case, eslint-disable-line -> allows ESLint to selectively ignore this line of checks while working

const str1 = "${name} is a coder" // eslint-disable-line

console.log(str1)
Copy the code

Re-running ESLint to check the eslint-configuration-comments.js file -> console does not report the previous error message:=> Use this to solve the problem: if there are multiple problems on a line, all problems are ignored -> Better to use eslint-disabled-line + the name of the rule to disable

Edit eslint – configuration – comments. Js

const str1 = "${name} is a coder" // eslint-disable-line no-template-curly-in-string

console.log(str1)
Copy the code

Run the ESLInt check:= > ESLint here at work when they will just ignore the specified rules Other rule still can be normal found = > annotation approach not only used to disable some rules Can also declared a global variable, modify a rule configuration, temporary began a certain environment and so on – > if you need can get through itEslint. Cn/docs/user – g…For specific use

7. ESLint with automation tools

We all know that ESLint is a stand-alone tool if you are currently in a project with automated workflows -> it is recommended that you integrate ESLint into automated workflows -> this has two advantages:

  • ESLint will definitely work after integration

    Automated builds are guaranteed in automated workflows. Integrating ESLint into the build process ensures that ESLint will work

  • Unified management with the project is more convenient

    The integration also makes it easier to manage and the project-related commands will be more uniform without Gulp and ESLint running between them

=> Preparatory work:

  • From github.com/zce/zce-gul… Cloning project
  • The dependency installation is complete
  • The ESLint module installation is complete
  • The gulp-esLint module is installed

Open the gulpfile. Js

Fold code -> Find the build task function that builds JS: A simple analysis shows that the JS build task uses Babel to convert source code. What we need to do now is to integrate ESLint operations into it -> because Gulp is a pipe working mechanism and ESLint integration should be done before Babel conversion ESLint -> Otherwise the code will no longer be true source code after Babel

Edit gulpfile. Js

.const script = () = > {
  return src('src/assets/script/*.js', { base: 'src' })
  .pipe(plugins.eslint())
  .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
  .pipe(dest('temp'))
  .pipe(bs.reload({ stream: true}}))...module.exports = {
  clean, build, develop, script
}
Copy the code

Then the current script task will perform ESLint on JS code before compiling Babel

Execute script tasks using gulp

yarn gulp script
Copy the code

After execution, the console reported an error:-> No ESLint configuration file found

Run the eslint script command again

This time the ESlit check was performed normally

Error code was intentionally written in mian. Js

.const a = 1
Copy the code

Run the eslint script command

This command can also be executed normally, which makes no sense -> since the initial assumption was that ESLint would be able to detect a problem and terminate subsequent compilation tasks -> why it succeeded here: By default, the ESLint plugin will only check for problems in the code and will not give any feedback based on the results. After ESLint completes processing, use ESLint’s format method to print the error message -> in the console. Then use ESLint’s failAfterError method to allow ESLint to terminate the task pipeline directly after checking for an error

Edit gulpfile. Js

.const script = () = > {
  return src('src/assets/script/*.js', { base: 'src' })
  .pipe(plugins.eslint())
  .pipe(plugins.eslint.format())
  .pipe(plugins.eslint.failAfterError())
  .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
  .pipe(dest('temp'))
  .pipe(bs.reload({ stream: true}}))...Copy the code

Run the script task again (yarn gulp script) on the command line -> The error message is displayed in the console:-> ESLint is now integrated into the JS editing task

8. ESLint with Webpack

8.1 ESLint with Webpack configuration

If you are currently developing a project that uses Webpack packaging, ESLint can also integrate into it -> only Webpack does not integrate into ESLint as a plugin, but via the Loader mechanism => Webpack before the module is packaged -> So ESLint can be integrated into Webpack as a Loader -> this allows ESLint to verify JS code before packaging it => Preparations in advance:

  • Through github.com/zce/zce-rea… Cloning of warehouse

  • Installing the corresponding module

  • Install the ESLint module

  • Install the ESLint-Loader module

  • Initialize the.eslintrc.js configuration file

    A normal React app is built using Webpack instead of using the official CLI tools

Edit webpack. Config. Js

const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
  mode: 'production'.entry: './src/main.js'.module: {
    rules: [
      // Currently all modules are handled by Babel-Loader. If you want to integrate ESLint with ESLint, you also need to use eslint-Loader to process them before babel-Loader -> because the modules are installed before babel-Loader
        / / here directly amend the JS use the Loader to the array Then eslint - loader on the back of the array - > it is important to note here: the order of the loader - > after the loader from here forward
        // Add a Loader rule to the JS file -> Add an enfore attribute to the rule with the value pre: Ensure that loaders configured in this rule have priority over other loaders (recommended).
      {
        test: /\.js$/,
        exclude: /node_modules/,        
        use: 'babel-loader'
      },
      // The second way
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: 'eslint-loader'.enfore: 'pre'},... ] },plugins: [
      new HtmlWebpackPlugin({
      	template: 'src/index.html'}})]Copy the code

Run the Webpack command on the command line

yarn webpack
Copy the code

After execution, the console reported an error:-> This is how ESLint is integrated into Webpack via Loader

8.2. Subsequent configuration of ESLint with Webpack

Eslint has already been integrated into webPack-using projects using eslint-Loader -> The next step is to add the corresponding esLint configuration to complete the subsequent code checks

View. Eslintrc. Js

The configuration here is just fine for the React project -> but the Webpack error (see 7.1) => find main.js and simply analyze the code itself-> Here React is not actually used -> here React is required after JSX code is compiled -> in this particular case ESLint will have to rely on some extra plug-in: eslint-plugin-react

Install eslint-plugin-react from the command line

cnpm i eslint-plugin-react -D
Copy the code

After installation, go to the node_modules directory and find the eslint-plugin-react module -> This module defines a number of validation rules that are specific to the React project -> Want to use these rules: This is configured using the plugins attribute in.eslintrc.js

Edit the eslintrc. Js

module.exports = { ...... .rules: {
  	// The value of the attribute can be set to Error/ WARN /off or 2/1/0
  	'react/jsx-uses-react': 2.// This rule prevents React from defining errors that are not being used
	},
  // The plugins value is an array. The members of the array can be directly specified to use certain plugins (the name of the plugin needs to be omitted from eslint-plugin).
  // After configuration, all rules in the Eslint-plugin-react module can be used
  plugins: [ 'react']}Copy the code

Perform Webpack packaging from the command line

yarn webpack
Copy the code

After execution: The console error message indicated that the previous React error did not appear=> Use the same method here -> replace it with a different rule: react/jsx-uses-vars

Edit the eslintrc. Js

module.exports = { ...... .rules: {
  	'react/jsx-uses-react': 2.'react/jsx-uses-vars': 2
	},
  plugins: [ 'react']}Copy the code

Run the Webpack package

The console does not output errors -> this is what plugins are for and basic use but for most ESLint plugins they do provide contributed configurations to reduce the cost of using them => the eslint-plugin-react used here exports two shared configurations: Recommended and All -> and now we use recommended -> this shared configuration can be used directly by inheritance -> but the syntax for inheritance is: plugin: plug-in name/shared configuration name

Edit the eslintrc. Js

module.exports = { ...... .extends: [
  	'standard'.'plugin:react/recommended']... .rules: {
  	 /* 'react/jsx-uses-react': 2, 'react/jsx-uses-vars': 2 */
	}/*, plugins: [ 'react' ]*/
}
Copy the code

The result of performing Webpack packaging is the same as without a shared configuration

9. Modernize projects to integrate with ESLint

With the popularity of frameworks like React or Vue, the ecology of frameworks has been very improved and the most obvious feeling is: Developing a React or Vue based project currently doesn’t require you to configure Webpack or ESLint engineering tools. The official CLI tools are already integrated with them => create one here using vue-CLI Vue.js as a demonstration

Use cli to install VUE

cnpm i @vue/cli -g
Copy the code

Run the vue create XXXX command to create a project

vue create syy-vue-app
Copy the code

Console interaction information:

One thing to noteLint on save: Verify automatically at Webpack build time: Lint and fix on commit: If a file is modified, Webpack will automatically compile it; if a file is modified, Webpack will automatically compile it; Commit -> use Git hooks to automatically verify the current code before git commit -> This ensures that all the code committed to the repository is verified

=> After the operation is complete -> vue-cli automatically installs the dependencies and creates the basic project structure at the end during which ESLint is integrated

Go to project -> Start project from the command line

cd syy-vue-app
npm run serve
Copy the code

Edit SRC /main.js to deliberately add error code

.const a = 1
Copy the code

After saving, the console output error message:-> In this way, developers do not need to spend too much time on the configuration and use of the tools. Developers can focus on the development of business functions

10. ESLint checks TypeScript

TypeScript is increasingly used in front-end projects. Here’s how ESLint validates TypeScript code: A case project, NPM initialization, ESLint module installation, TypeScript module installation– > this note must be installed TypeSc module Otherwise in the subsequent ESLint configuration file will be generated an error – > for Lint TypeScript code Could have been used before tslint tools But then tslint official put up the maintenance Instead, we suggest that we use ESLint with TypeScript plugins to implement TypeScript validation

Initialize the ESLint configuration action

yarn eslint --init
Copy the code

One caveat here: Select Yes -> when a TypeScript module is involved in the problem delivery. The last interaction requires the installation of two additional modules that ESLint requires to check TypeScript code

After that, you can use ESLint directly to check TypeScript code

Editing the ts

function foo (ms: string) :void {
  console.log(msg)
  
}

foo("hello TS ~")
Copy the code

View. Eslintrc. Js

The reason you need to configure a parser is because TypeScript has a lot of special syntax compared to normal JS code

Verify index.ts by running the command

yarn eslint ./index.ts
Copy the code

After execution, the console reported an error:

11. StyleLint

StyleLint checks for normal CSS code

In addition to JS code that needs to be Lint, CSS code also needs to be Lint -> CSS Lint uses the StyleLint tool to do this

StyleLint:

  • Provides default code checking rules
  • Provides quick invocation of the CLI tool
  • Supports the Sass Less PostCSS through plug-ins
  • Supports Gulp or Webpack integration

=> Preparation: NPM initialization, CSS and Sass file preparation

Install the StyleLint module on the cli

cnpm i stylelint -D
Copy the code

After the installation, you can find the stylelint CLI command in the node_modules/.bin directory. Once you have this command, you can check the style file code with this command

Run StyleLint on the command line to check index. CSS

yarn stylelint ./index.css
Copy the code

Console output error: no corresponding configuration file was found

Manually add.stylelintr.js to the root directory and edit it

The StyleLint configuration items are basically the same as those in ESLint

module.exports = {
  StyleLint does not have any shared configuration available internally, so you need to install some modules of your own
  extends: "",}Copy the code

Install stylelint-config-standard

Stylelint-config-standard: indicates the stylelint shared configuration module

cnpm i stylelint-config-standard -D
Copy the code

Edit the stylelintrc. Js

After installation, use the module directly -> but there are some differences from ESLint: the shared configuration name here must be a completed module name

module.exports = {
  extends: "stylelint-config-standard"
}
Copy the code

Check index.css again on the command line

yarn stylelint ./index.css
Copy the code

This time you can find the problem in the CSS code:-> You can also automate most problems directly by using the –fix command line argument

11.2. StyleLint checks the Sass code

If you need to use StyleLint to verify Sass code in a project -> install another module: stylelint-config-sass-Guidelines -> Install Sass plug-in with StyleLint in this module

Use the cli to install stylelint-config-sass-guidelines

cnpm i stylelint-config-sass-guidelines -D
Copy the code

Edit the stylelintrc. Js

module.exports = {
  extends: [
    "stylelint-config-standa"."stylelint-config-sass-guidelines"]}Copy the code

Run the StyleLint command to check index.sass

yarn stylelint ./index.sass
Copy the code

StyleLint detects a problem with Sass code after execution:< span style = “box-sizing: border-box; color: RGB (50, 50, 50); line-height: 22px; font-size: 16px! Important; word-break: block;

If you want to integrate StyleLint into Gulp or Webpack, you can refer to ESLint’s integration method

12. Use of Prettier

Prettier is a common front-end code formatting tool used frequently in recent years. It is very powerful and can format almost all types of code files. In daily use, Prettier can also be used to automatically format code or for markdown In short, Prettier can easily implement the standardization standards in front-end projects and its use is very simple

=> Prepare in advance: prepare different code files that can be encountered during daily front-end development

Install Prettier on the CLI

yarn i Prettier -D
Copy the code

After the prettier command on the prettier module is used to format the test code

Run the prettier command to format style. CSS

yarn prettier ./style.css
Copy the code

After the command is executed: The console outputs the formatted CSS code -> by default, the prettier command outputs the formatted CSS code directly to the console -> To overwrite the formatted CSS code directly -> add the command line parameter “write” to the end

Run the prettier command to overwrite the formatted code on the source file

yarn prettier ./style.css --write
Copy the code

After the Prettier command is executed, the Prettier command automatically formats the file

Using wildcards on the command line, format all the code at once

yarn prettier . --write
Copy the code

After the command “prettier” is executed, all codes are formatted and the source file is overwritten

13. Git Hooks work mechanism

Here are Git some Hooks with content is introduced Because you need to use in the subsequent ESLint and the combination of the Git Hooks – > currently have to understand the importance of code standardization and how to through the use of some tools to ensure that the code specification – > However, there are still some problems left out in the process. Not performing Lint work before the code is submitted to the repository -> This can result in the entire project not passing CI -> So the Lint tool loses its meaning -> The Lint tool is used to ensure that the code is submitted to the repository without problems And the format is good -> how can we solve this problem? => Force Lint to commit code using Git Hooks

=> Git Hooks introduction

  • Git Hooks are also called Git Hooks, and each hook corresponds to a task

    Each hook is attached to a specific Gti operation Ex: Commit push

  • Shell scripts allow you to write specific actions to be performed when the hook task is triggered

    Find a specific hook by writing a specific shell script that defines the task to be performed when the hook action is triggered: pre-commit hook -> trigger before commit

14. ESLint combines Git Hooks

Requirement: Forcing Git hooks to Lint code before it’s committed => Here’s a real problem: Currently, many front-end developers are not good at using shell scripting, which is currently a must, so someone developed an NPM module: The use of Husky -> Git Hooks can be implemented without having to write shell scripts

=> Initial preparation: NPM initialization, ESlint configuration initialization script, used to test index

Install the HUSky module from the command line

cnpm i husky -D
Copy the code

The editor package. Json

{
  "script": {
    "ESLint": "eslint ./index.js"},... ."husky": {
  	"hooks": {
  		"pre-commit": "npm run ESLint"}}}Copy the code

Editing the js

const a = 1

3333
Copy the code

Commit to the repository through the command line code

git add .
git commit -m '111'
Copy the code

Lint error => Console output after execution:-> < p style = “text-align: center; Lint operations will be performed before the code is committed -> Code will not be committed to the repository if there is an error in Lint -> This already allows the developer to check the code before committing => But if you want to do some subsequent operations after the check Ex: Format the examined code or add the formatted code to the temporary area -> At this point husky becomes insufficient

Lint-staged: Husky continues to provide some additional functionality

Lint-staged is installed from the command line

cnpm i lint-staged -D
Copy the code

The editor package. Json

{... ."script": {
    "ESLint": "eslint ./index.js"."preCommit": "lint-staged"},... ."husky": {
  	"hooks": {
  		"pre-commit": "npm run preCommit"}},"lint-staged": {
    "*js": [
      "eslint"."git add"]}}Copy the code

Run the commit command

git add .
git commit -m '222'
Copy the code

After execution, it is found that the esLint and Git add operations have been executed in sequence-> This makes it possible to enforce validation of the submitted code before it is submitted, and also to perform other operations after the latter verifies the code before it is submitted