Why have normative standards

  • Software development requires multiple people to work together
  • Different developers have different coding habits and preferences
  • Different preferences and habits increase project maintenance costs
  • Each project or team needs to have clear and consistent standards to avoid the complications of inconsistency

Where do I need standardization standards

  • Code, documentation, commit logs
  • An artifact of development
  • Code standardization specifications are most important

Methods for implementing standardization

  • Standard convention for encoding predecessors
  • Implementation via tools (Lint) is more reliable and convenient

Common implementations of canonicalization

With the combination of EditorConfig + Prettier + ESLint, code can be checked, restricted and beautified in the development process of team members through unified convention configuration in a project, and unified coding style can save a lot of communication costs, expose code defects in advance, and reduce the risk of second code modification in the later period.

  • EditorConfig: Code across editors and ides with a consistent simple coding style;
  • Prettier: a tool that formats code, beautifies it;
  • SLint: code quality checks, code style constraints, etc.

They have their own scope, and we’ll focus on ESLint.

ESLint introduction

The most popular javascript Lint tool

  1. Monitor JS code quality.
  2. ESLint makes it easy to unify developer coding styles.
  3. ESLint can help developers improve their coding.

Use the ESLint tool

Installation steps: Initialize the project → install the ESLint module as a development dependency → verify the installation using CLI commands

npm init

npm install eslint --dev

Eslint provides a cli program. After installation, an ESLint executable file will be generated in the node_modules/. Bin directory of the project. Locate the esLint file in the directory on the terminal and check the version number by calling –version.

cd .\node_modules\.bin\

.\eslint --version



Or use the shortcut to go directly to the CLI:

npx eslint --version(NPX is the latest version of NPM integration tool)

yarn eslint --version

  • Customize ESLint validation rules

NPX ESLint — Lint recommends choosing the third option (checking syntax, problematic code, code style) for maximum code quality.

NPX esLint NPX eslint.src \test.js the first time esLint is executed, a syntax error will be thrown. If the syntax problem is not resolved, Eslint has no way to detect problematic code and code styles. Follow the prompts to resolve the syntax at this point, and then you can use –fix to fix most of the problematic code and style. npx eslint npx eslint .\src\test.js –fix

It is recommended to manually correct problematic code and code style first to develop good coding habits. Eslint is only used as a tool to make a final check

.eslintrc.js basic configuration comments (as follows) :

/ / CommonJS syntax
module.exports = {
  // Marks the final running environment of the current code
  env: {
    browser: true.// Browser environment, can use document, window
    es2021: true
  },
  // Set multiple share configurations
  extends: [
    'plugin:vue/essential'.'standard'].// Just check the syntax, the specific member is available depends on the runtime environment
  parserOptions: {
    ecmaVersion: 'latest'  / / ECMAScript version
  },
  plugins: [
    'vue'].// ESLint Shuts off, warns WARN, and reports errors for each rule
  rules: {},Declare additional global members, such as global jQuery objects
  globals: {
    "jQuery": "readonly"}}Copy the code

To disable ESlint validation on the current line, add the following comment // eslint-disable-line disables all rule validation by default, You are advised to add the name of the rule to be disabled // eslint-disable-line no-template-culy-in-string

const str = "${name} is a coder" // eslint-disable-line no-template-culy-in-string
Copy the code

ESLint combines automation tools or Webpack

Inheriting from automated tools makes ESLint work and project unified and easier to manage

  1. Use gulp automation tools (for gulpfile.js) (you need to install the modules to use in advance).
// gulpfile.js In the gulp configuration file, add eslint checks to the JS build task
const plugins = require("gulp-load-plugins")

const script = () = > {
    return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format())
    .pipt(plugins.eslint.failAfterError())
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true}}))Copy the code
  1. Combined with Webpack (modules that need to be installed in advance)

Webpack Module rules: Loaders are executed from right to left and from bottom to top

// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    mode: 'production'.entry: './src/main.js'.module: {
        rules: [{
            test: /\.js$/,
            exclude: /node_modules/,
            use: 'babel-loader'
        }, {
            test: /\.js$/,
            exclude: /node_modules/,
            use: 'eslint-loader'.enforce: 'pre'
        }, {
            test: /\.css$/,
            use: ['style-loader'.'css-loader']]}},plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'}})]Copy the code

In the modern Vue and React framework projects, their CLI tools have been integrated with webPack, ESLint, etc., so we don’t have to spend a lot of time configuring the use of tools. Developers can focus more on business development.

  • ESLint support for Typescript

Tslint has officially abandoned the maintenance of using parser to specify a syntax parser

// .eslintrc.js
module.exports = {
  env: {
    browser: true.es2021: true
  },
  extends: [
    'plugin:vue/essential'.'standard'].// parser: Specifies a syntax parser
  parser: '@typescript-eslint/parser'.parserOptions: {
    ecmaVersion: 'latest'
  },
  plugins: [
    '@typescript-eslint'].rules: {},}Copy the code
  • Use of Stylelint tool

ESLint is a check for JS; Stylelint is a check for style.

  • Provides default code review rules
  • Provides CLI tools, quick call
  • Supports Sass and Less PostCss through plug-ins
  • Support for gulp or Webpack inheritance

Installation of the NPM I stylelint -d requires manual installation of the shared configuration module before inheritance. For example, stylelint-config-standard, for example, stylelint-config-sass-guidelines verify sASS code new.stylelintrc.js

// .stylelintrc.js
module.exports = {
    extends: [
        "stylelint-config-standar"."stylelint-config-sass-guidelines"]}Copy the code

A derivative based on ESLint

Prettier: a powerful, universal front-end code formatting tool that formats almost all types of file code

NPM I prettier -d prettier -d CSS NPX prettier style. CSS –write NPX prettier style. –write(Format all files)

Do not rely too much on formatting verification tools, in the programming process should strictly follow the standard format coding

ESLint incorporates Git Hooks

Enforce Lint checking before committing code via Git Hooks

Git Hooks Are also called Git Hooks, which correspond to one task. Hook tasks can be written using shell scripts

For those who are not good with shells, you can implement Git Hooks in conjunction with Husky’s NPM module.

// package.json implements mandatory formatting code before submission
{
    "scripts": {
        "precommit": "lint-staged"
    },
    "husky": {
        "hooks": {
            "pre-commit": "npm run test"}},"lint-staged": {
        "*.js": {
            "eslint"."git add"}}}Copy the code

If it helps you, please move your little finger and give me a thumbs-up