Front-end specification implementation, team-level solutions

foreword

This article mainly talks about the problems encountered in front-end development that are difficult to implement coding specifications and solutions, including coding specifications and git commit specifications.

The focus is on the operation of implementing the coding standards of the front-end team. Follow me step by step, and you will be able to implement the norm.

Q: Do you want to develop coding standards? Should I use ESLint? Do you want to normalize git commits? A: For non-personal projects I recommend coding according to team or mainstream norms. Writing code and reading code are two different things, and when working as a team, it’s best to code that everyone feels comfortable looking at. The same is true for git logs, writing and reading are two different things.

If there is no development specification for the project developed by the team:

  • Maintenance costs will likely increase in the future.
  • May not understand the code of colleagues (coworkers may not understand your code).
  • Projects do not scale easily.
  • When the company's personnel flow, it is difficult to hand over projects.
  • ugly!

Such code is very ugly

const userInfo ={
  name: "Zhang San",
  age:20,
  gender: 'male'
}

function showUserInfo() {
  console.log('Name:'+userInfo.name)
console.log("age:" + userInfo.age);
console.log("gender:" +userInfo.gender);
}

showUserInfo()
  • Use single quotes in some places and double quotes in others.
  • userInfo ={...} There is no space after the equal sign.
  • age:20 No space after the colon.
  • The code in showUserInfo has two lines typed without tabs.
  • Some codes have semicolons, some codes do not.
  • When strings are concatenated, there are no spaces on both sides of some plus signs.

Although this code works, it looks very ugly. Even in many companies, this kind of code is unqualified, and there is a high probability that it will be publicly executed.

As for what specification to use (such as whether to add a semicolon or not), this article does not discuss in depth. You can code according to the specifications negotiated by the team, or you can use the specifications provided by the big manufacturers.

πŸŽ—οΈAt the end of the article, there are several links to the specifications of the big manufacturers~

Problems caused by normalization

Having a specification is a good thing, but it also raises some questions:

  • The ability of team members is uneven, and some members will be forced to reduce development efficiency according to high standards.
  • When a new member joins, do you need to read the specification document in its entirety? You may not remember after watching it.

solution

In response to the above problems, the more popular solution is now: automation!

  • When saving the code: Automatically format the code, and then check whether the code conforms to the team's specifications, and prompt errors for non-compliance.
  • When submitting code: Check whether the code conforms to the team's specifications, and if it is not in compliance, it is not allowed to submit.
  • When writing a commit message: Provide a log template.

That is to say

  • Check coding conventions with ESLint;
  • Automatically save to a planned format with the Prettier plugin;
  • Commit specs with Commitizen conventions;

hands-on

The case running environment and editor of this article

  • node ^16.13.1
  • npm ^8.1.2
  • @vue/cli ^4.5.15
  • Used VS Code editor

I will use vue-cli to create a Vue project as a demonstration, and the React project is actually similar. The following code and syntax will basically not depend on vue, because this article is about code specifications and Git submission specifications.

1. Create a project

1.1. Create a project with vue-cli

Students who have not installed vue-cli can use this command to install it.

npm install -g @vue/cli

Then use vue-cli to create the project.

# [Step 1] Create a project using the command
vue create Project name (lowercase English)

######################################################

# [Step 2] Choose a template
? Please pick a preset: Manually select features
Vue CLI v4.5.15
? Please pick a preset: (Use arrow keys)
  Default ([Vue 2] babel, eslint)
  Default (Vue 3) ([Vue 3] babel, eslint)
> Manually select features  # Select this to match manually

######################################################

# [Step 3] Select the desired function. Please choose according to your own project. This article only does code specification, so I did not choose vuex, routing, css preprocessor.
? Check the features needed for your project: (Press <space> to select, <a> to toggle all, <i> to invert selection)
 (*) Choose Vue version
 (*) Babel
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support
 ( ) Router
 ( ) Vuex
 ( ) CSS Pre-processors
>(*) Linter / Formatter  # Code formatting, remember to select this!
 ( ) Unit Testing
 ( ) E2E Testing
 
######################################################

# [Step 4] Select the Vue version. This article uses 3.x.
? Choose a version of Vue.js that you want to start the project with
  2.x
> 3.x

######################################################

# [Step 5] Select the specification scheme.  vue-cli provides several sets of specifications by default, I chose the ESLint standard specification
? Pick a linter / formatter config:
  ESLint with error prevention only
  ESLint + Airbnb config
> ESLint + Standard config  # ESLint Standard Specification Scheme
  ESLint + Prettier

######################################################

# [Step 6] Select the operation of detecting code specification (when saving, when submitting), here I have selected it.
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
 (*) Lint on save  # Detect on save
>(*) Lint and fix on commit  # Detect on commit

######################################################

# [Step 7] Where do you prefer to put Babel, ESLint, etc. configuration?  
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
> In dedicated config files  # separate configuration file
  In package.json

######################################################

# [Step 7] Save this as a preset for future projects? I chose not to: n
? Save this as a preset for future projects? (y/N) n

After a long wait, the project was created successfully.

Run the project:

cd project directory
npm run serve

2. Configure ESLint rules

ESLint is a code detection tool. In the previous step of creating a project, we have integrated ESLint into the project.

Students who are not very clear about ESLint can see the introduction on the official website: γ€ŽESLint』

2.1 Configuration

Open the .eslintrc.js file in the root directory to see the default configuration items.

module.exports = {
  root: true, // Whether the current file is in the root directory of the project
  env: { // Environments with ESLint detection enabled
    node: true // Start ESLint detection in node environment
  },
  extends: [ // Basic configuration items that need to be inherited
    'plugin:vue/vue3-essential',
    '@vue/standard'
  ],
  parserOptions: { // specified parser
    parser: 'babel-eslint'
  },
  /*
   * This is very important, the main configuration rules of the project are written here! ! ! ! ! !
   * For example: Is console allowed in the project?  Are double quotes allowed to wrap strings? ...
   *
   * "off" or 0 - turn off the rule
   * "warn" or 1 - turn on the rule, use warning level errors: warn (does not cause the program to exit)
   * "error" or 2 - enable the rule, use the error level error: error (when triggered, the program will exit)
   */
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'space-before-function-paren': 'off'
  }
}

2.2 Testing

The current project uses single quotes to wrap strings in JS by default. If you use double quotes at this time, an error will be reported.

You can try to modify App.vue

/* omit part of the code */
<script>
export default {
  name: "App"  // Double quotes are used here
}
</script>

When using double quotes to wrap a string, ESLint will prompt the following error

E:\practice\vue\vue3\vue3-demo1\src\App.vue
  10:9  error  Strings must use singlequote  quotes

βœ– 1 problem (1 error, 0 warnings)
  1 error and 0 warnings potentially fixable with the `--fix` option.

It will prompt the wrong file, the number of lines, and the number of columns. Then it gives a prompt error Strings must use singlequote quotes , meaning "strings must use single quotes".

If your team is accustomed to using double quotes and adding semicolons after statements, these configurations can be checked on Baidu. This article does not intend to explain in depth on Coding Specifications, because each team has a different style.

3. Install the code formatting plugin Prettier

Prettier can automatically format your code to specifications for you. "Prettier Chinese Network"

3.1 Install Prettier

Many times your coding style has become a habit, and it is difficult to change it after entering a new team. If there are frequent error reminders of coding standards, it will really affect the development speed.

At this point Prettier can help you. Prettier can automatically format code according to the rules you set when you save.

I mainly use the editor VS Code, so I can find Prettier directly in the plugin market and just click to install it.

3.2 Configuration scheme

After installing the Prettier plugin, you can configure the automatic formatting scheme according to the requirements of your project specification.

Create a .prettierrc file in the project root directory. This file tells Prettier how to format the code.

The following configuration can be written in it:

{
  // Do not use semicolon syntax
  "semi": false,
  // use single quotes
  "singleQuote": true,
  // The last line of the object does not add a comma
  "trailingComma": "none"
}

More configurations can be found on Baidu or at "Prettier Chinese Network" Check it out.

3.3 Set to automatically format code when saving

Open the VS Code settings panel: File - Preferences - Settings

Then enter save in the search bar and check Editor: Format On Save.

It should be noted that if the configuration of ESLint or Prettier does not take effect, please re-run the project.

4. Conventional submission specifications

git commit should also be standardized, and it is best to provide a template for submission.

4.1 Good specification!

What I talked about above is the normative constraints during coding. In fact, there is another specification that many people have not noticed, and it is the version information specification.

Let's take a look at what is a good specification

Each record has a functional description, followed by a brief description of the submission.

4.2 Problems encountered

The above example looks very comfortable, but will it be troublesome to write this every time? How do you ensure that everyone writes to the same specification? For example: someone wrote "fix bug", someone wrote "fix bug".

4.3 Solution

Use the "conventional commit specification".

The so-called convention submission specification is actually to provide a set of templates for you to choose the general direction of this submission, and finally simply write a sentence or two of this submission description.

The convention commit specification is the most discussed Angular Team Specification extended Conventional Commits specification . Interested can take a look.

Conventional submission specification format:

<type>[optional scope]: <description>

<type>[optional range]: <describe>

Type is a bunch of options that don't require manual input from the user. This solves one of the problems mentioned above.

4.4 Hands-on implementation

Implemented with Commitizen and cz-customizable. And use git cz instead of git commit .

4.4.1 Installation

npm install commitizen cz-customizable -dev

Use the above command to install commitizen and cz-customizable.

The reason why -g is not installed globally is because the new partners who take over the project may not have commitizen installed on their own computers. At this time, it can also be used normally with the installation in the project.

If you commit frequently using this specification, it is recommended that you install commitizen globally.

However, cz-customizable is still recommended to be installed in the project -dev , so that each project can be configured independently.

4.4.2 Configuration

Add the following configuration to package.json:

/* omit part of the code */
"config": {
  "commitizen": {
    "path": "node_modules/cz-customizable"
  }
}

Create a .cz-config.js file in the project root directory and add the following configuration:

module.exports = {
  // optional type
  types: [
    { value: 'feat', name: '⚑ feat: new function' },
    { value: 'fix', name: 'πŸ› fix: repair Bug' },
    { value: 'docs', name: '✏️ docs: Documentation changes' },
    { value: 'style', name: 'πŸ’„ style: Changes that do not affect the meaning of the code(whitespace, formatting, missing semicolons, etc.)' },
    { value: 'refactor', name: '♻️ refactor: Refactor the code to neither fix bugs nor add features' },
    { value: 'perf', name: '⚑ perf: performance optimization' },
    { value: 'test', name: 'βœ… test: test related' },
    { value: 'ci', name: 'πŸ‘· ci: Change continuous integration files and scripts' },
    { value: 'chore', name: 'πŸ“¦ chore: chores such as repackaging or updating dependent tools' },
    { value: 'revert', name: 'βͺ revert: code fallback' },
    { value: 'WIP', name: '🚧 WIP: Work in progress' }
  ],
  // scope type (after definition, it can be selected by up and down keys)
  scopes: [
    ['components', 'component related'],
    ['hooks', 'hook related'],
    ['utils', 'utils related'],
    ['element-ui', 'right element-ui adjustment'],
    ['styles', 'style related'],
    ['deps', 'project dependencies'],
    ['config', 'configuration related'],
    ['other', 'other modifications'],
    // If you choose custom, you will be asked to enter a custom scope later. You can also leave this option unset and set the following allowCustomScopes to true
    ['custom', 'none of the above? i want to customize']
  ].map(([value, description]) => {
    return {
      value,
      name: `${value.padEnd(30)} (${description})`
    }
  }),

  // step message
  messages: {
    type: 'Make sure this submission follows the spec!\n Select the type you want to submit:',
    scope: '\n choose one scope(optional):',
    customScope: 'Please enter a modification range (optional):',
    subject: 'Please enter a description of the change (required):',
    body: 'Fill in a more detailed change description (optional):',
    footer: 'Please enter the ISSUES (optional):',
    confirmCommit: 'confirm submission?'
  },
  // Allow custom scope
  allowCustomScopes: true,
  // question to skip
  skipQuestions: ['footer'],

  // The default value of the subject text is 72
  subjectLimit: 100
}

4.4.3 Use

At this point, you can use git cz instead of git commit.

After the above configuration, you can use git add . Submit the changes to the staging area, and then use git cz to submit a version.

git add .

git cz

After entering git cz, start choosing the type of commit

Select the scope of the change

After that, there will be a series of prompts, some of which are required.

Finally, after confirming the submission, a version can be generated.

Finally, use git log to view the history of commits.

canonical reference

airbnb specification

google specification

Baidu EFE Specification

JD Aotu Specifications

JS code remark specification: JSDoc

Ruan Yifeng's Commit message and Change log writing guide

If this article is helpful to you, please give me a like, and you can also recommend this article to your friends.

Posted by AMCH on Thu, 02 Jun 2022 06:19:02 +0530