The front end is standardized and team level solutions are implemented

preface

This paper mainly talks about the problems and solutions encountered in front-end development, including coding specification and git commit specification.

Focus on the implementation of front-end team coding standards. Follow me step by step, and you will be able to implement the norms.


Q: do you want to develop coding specifications? Do you want to use ESLint? Do you want to standardize git submission?

A: for non personal projects, I suggest coding according to team or mainstream specifications. Writing code and reading code are two different things. If you work in a team, it's best that the code can make everyone feel comfortable. 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:

  • The maintenance cost rate will probably become higher in the future.
  • You may not understand your colleagues' code (and your colleagues may not understand your code).
  • The project is not easy to expand.
  • When the company's personnel flow, it is difficult to hand over the project.
  • Ugly!


For example, such code is very ugly

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

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

showUserInfo()


  • Single quotation marks are used in some places and double quotation marks are used in some places.
  • userInfo ={...} There is no space after the equal sign.
  • age:20 there is no space after the colon.
  • There are two lines of code in showUserInfo that are formatted without tabs.
  • Some codes have semicolons, and some codes have no semicolons.
  • When string splicing, there is no space on either side of the plus sign.


Although this code can run, it looks very ugly. Even in many companies, this code is unqualified and will probably be publicly punished.


As for what specifications to use (such as whether to add semicolons or not), this paper will not discuss them in depth.
You can code according to the specifications negotiated by the team, or you can use the specifications provided by large manufacturers.


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



Problems caused by standardization

Having norms is good, but it also raises some problems:

  • The abilities of team members are uneven, and some members will be forced to reduce development efficiency according to high-standard specifications.
  • When new members join, do you want to read the specification documents completely? You may not remember it after reading it.



Solution

For the above problems, the more popular solution is: automation!

  • When saving the code: automatically format the code, and then check whether the code meets the team specifications. If it does not comply, an error will be prompted.
  • When submitting Code: check whether the code complies with the team specification. If it does not comply, it is not allowed to submit.
  • When writing a commit message: provide a log template.


in other words

  • Check the coding specification with ESLint;
  • Automatically save to planning format with Prettier plug-in;
  • Submit specifications with the commit contract;




Do it

This paper introduces the case running environment and editor

  • node ^16.13.1
  • npm ^8.1.2
  • @vue/cli ^4.5.15
  • The VS Code editor is used

I will use Vue cli to create a Vue project as a demonstration. In fact, the practice of React project is similar.
The following code and syntax will not rely on vue, because this article is about code specification and Git submission specification.



1. Create project

1.1. Create a project using 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] use the command to create a project
vue create Project name (in figures and English)

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

# [step 2] Select 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 required function. Please choose according to your project. This article only makes code specifications, so I didn't choose vuex, routing and 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 choose this!
 ( ) Unit Testing
 ( ) E2E Testing
 
######################################################

# [step 4] Select Vue version. This paper 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 specifications (when saving, when submitting), and I have selected them here.
? 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 submission

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

# [step 7] where do you prefer Babel, ESLint and other configurations?  
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
> In dedicated config files  # Separate profile
  In package.json

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

# [step 7] save this as the default for future projects? I choose not to: n
? Save this as a preset for future projects? (y/N) n

After a long wait, the project was created successfully.


Run project:

cd Project directory
npm run serve



2. Configure ESLint rules

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

Students who are not familiar with ESLint can see the introduction on the official website: γ€ŽESLint』


2.1 configuration

Open the in the root directory eslintrc.js file, you can see the default configuration items.

module.exports = {
  root: true, // Is the current file at the root of the project
  env: { // Environment with ESLint detection enabled
    node: true // Start ESLint detection in node environment
  },
  extends: [ // Basic configuration items to be inherited
    'plugin:vue/vue3-essential',
    '@vue/standard'
  ],
  parserOptions: { // Indicates the 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? Allow double quotation marks to wrap strings
   *
   * "off" Or 0 - close rule
   * "warn" Or 1 - turn on the rule and use the error of warning level: warn (it will not cause the program to exit)
   * "error" Or 2 - open the rule and 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 quotation marks to wrap the string in JS by default. At this time, if double quotation marks are used, an error will be reported.

You can try to modify the app vue

/* Omit some codes */
<script>
export default {
  name: "App"  // Double quotes are used here
}
</script>


When you wrap a string in double quotation marks, 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 file with error, the number of rows and columns. Then a prompt error strings must use single quote quotes is given, which means "strings must use single quotation marks".


If your team is used to using double quotation marks and adding semicolons after sentences, these configurations can be checked by Baidu. This article does not intend to explain in depth the coding specifications, because the styles of each team are different.



3. Installing the code formatting plug-in Prettier

Prettier can automatically help you format code according to specifications. "Prettier Chinese website"


3.1 installing Prettier

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

Prettier can help you now. Prettier can automatically format the code according to the rules you set when you save.


I mainly use the VS Code editor, so I can find Prettier directly in the plug-in market and click Install directly.


3.2 configuration scheme

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

Create in the project root directory Pretierrc file, which tells Prettier how to format code.

The following configuration can be written:

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

More configurations can be in Baidu or "Prettier Chinese website" Consult.


3.3 automatically format code when saving settings

Open the VS Code settings panel: File - preferences - settings


Then enter save in the search field, and then check Editor: Format On Save.


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



4. Agreed submission specification

git commit should also be standardized. It is best to submit it by providing templates.


4.1 good specification!

What I mentioned earlier is the specification constraints during coding. In fact, there is another specification that many people do not notice, which is the version information specification.

Let's take a look at the good specifications:

Each record has a function description, and then briefly describe the description submitted this time.


4.2 problems encountered

The above example looks very comfortable, but will it be troublesome every time? How to ensure that everyone writes according to the same specification? For example, some people write "fix bug s" and others write "fix vulnerabilities".


4.3 solutions

Use contractual submission of specifications.


The so-called agreed submission specification actually provides a set of templates for you to choose the general direction of this submission, and finally simply write one or two sentences of this submission description.

The Convention submission specification is most discussed Angular team specification Extended Conventional commitments specification . If you are interested, you can have a look.


Agreed submission Specification Format:

<type>[optional scope]: <description>

<type>[Optional range]: <describe>


Type is a pile of options, which does not need to be entered manually by the user. In this way, one of the problems mentioned above can be solved.


4.4 implementation

It is implemented with Commitizen and CZ customizable. And use git cz instead of git commit.


4.4.1 installation

npm install commitizen cz-customizable -dev

Using the above command, you can install committed and CZ customizable.

The reason why the global installation -g is not allowed here is that the new project partner may not have commitizen installed on his own computer. At this time, it can also be used normally after it is installed in the project.

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

However, CZ customizable is recommended to install - dev in the project, so that each project can be configured independently.


4.4.2 configuration

In package Add the following configuration to JSON:

/* Omit some codes */
"config": {
  "commitizen": {
    "path": "node_modules/cz-customizable"
  }
}


Create in the project root directory cz-config.js file 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: Document change' },
    { value: 'style', name: 'πŸ’„ style: Changes that do not affect the meaning of the code(Blank, formatted, missing semicolon, etc)' },
    { value: 'refactor', name: '♻️ refactor: Refactor the code without fixing errors or adding functionality' },
    { 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: 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 relevant'],
    ['utils', 'utils relevant'],
    ['element-ui', 'yes element-ui Adjustment of'],
    ['styles', 'Style related'],
    ['deps', 'Project dependency'],
    ['config', 'Configuration related'],
    ['other', 'Other modifications'],
    // If you select custom, you will be asked to enter a custom scope later. You can also set allowcustoms to true without setting this item
    ['custom', 'None of the above? I want to customize']
  ].map(([value, description]) => {
    return {
      value,
      name: `${value.padEnd(30)} (${description})`
    }
  }),

  // Step message prompt
  messages: {
    type: 'Ensure that this submission complies with the specifications!\n Select the type you want to submit:',
    scope: '\n Select one scope(Optional):',
    customScope: 'Please enter the modification range (optional):',
    subject: 'Please enter change description (required):',
    body: 'Fill in a more detailed description of the change (optional):',
    footer: 'Please enter the to close ISSUES (Optional):',
    confirmCommit: 'Confirm submission?'
  },
  // Allow custom ranges
  allowCustomScopes: true,
  // Questions to skip
  skipQuestions: ['footer'],

  // The default value of 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 the version again.

git add .

git cz


After entering git cz, you start selecting the type of submission


Select the scope of the change


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


After confirming the submission, a version can be generated.


Finally, use git log to view the submitted history.




Specification reference

airbnb specification


google specification


Baidu EFE specification


JD Aotu specification


JS code remark specification: JSDoc


Ruan Yifeng's writing guide for Commit message and Change log



If this article is helpful to you, please give me a praise. At the same time, you can also recommend this article to your friends.

This article is composed of blog one article multi posting platform OpenWrite release!

Keywords: Javascript Front-end html5 Vue.js css

Added by pococool on Sun, 09 Jan 2022 17:09:14 +0200