• Column address: Front-end compilation and engineering
  • Author: Front-end Xiao Dong

One, foreword

The programming format specification has been followed by all the major Internet companies, some of which have their own published specifications, such as:

  • Jingdong Concave laboratory front-end code specification
  • Tencent front-end code specification
  • Baidu front-end code specification document

Overall specifications can be broadly divided into two categories:

(1) Code format specification

Eslint+Prettier+Vscode for code format specification, Eslint+Prettier+Vscode can automatically normalize code format when saving code.

(2) Code submission specifications

For the code submission specification, we monitor git hooks using husky and configure them using the following plug-ins:

  1. commitlint: Used to detect submitted information
  2. lint-staged: Check the updated code for this modification, and fix it automatically and can be added to the staging area
  3. pre-commit:git hooksCheck code compliance before submitting it. Non-compliance will not be submitted
  4. commit-msg:git hooksHooks are checked before code is submittedcommitWhether the information conforms to the specification
  5. commitizen:gitA standardized submission tool to help you fill outcommitInformation, accord withContract submissionrequirements

Second, code format specification

(1) Initialize a project

(2) InstallationESlint
npm install eslint --save-dev
Copy the code

After the installation, open the terminal and run the command NPX elint –init to generate the configuration according to your requirements:

Eslintrc.js file in the root directory:

module.exports = {
    "env": {
        "browser": true."es2021": true."node": true
    },
    "extends": "eslint:recommended"."parserOptions": {
        "ecmaVersion": 12."sourceType": "module"
    },
    "rules": {}};Copy the code

To test this, add an index.js file and type:

Console execution command:

npx eslint index.js
Copy the code

Error: EsLint is enabled, we added rule no-console to.eslintrc.js:

module.exports = {
    "env": {
        "browser": true,
        "es2021": true,
        "node": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "rules": {
    	"no-console": "off"
    }
};
Copy the code

Rules You can configure many rules. For details, see Eslint Rules

Then change index.js to:

Execute again:

npx eslint index.js
Copy the code

The console no longer reports errors and can output variables normally.

(3) Vscode installs Eslint plugins

NPX ESLint XXX will be executed each time to verify that a single file is fine, multiple files will not be playable. Is there a way to automatically execute Eslint when code is saved, simply by installing the Eslint plugin:

Add the following content to the setting.json file (it should be added automatically after installing the Eslint plugin, if not manually) :

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

An error message will appear in the editor:

Add the eslint command to the package.json script to say that ESlint checks all files in the current directory:

"scripts": {
    "eslint": "eslint ./**/*"
}
Copy the code

Add the. Eslintignore file in the root directory to exclude the following files from Eslint detection:

node_modules
package.json
package-lock.json
Copy the code

Add a new test.js file:

Then enter the command on the console:

npm run eslint
Copy the code

Multiple files can now be detected.

(4) Use Prettier for automatic repair

Eslint can help us detect code by automatically fixing code using Prettier to make our code conform to Eslint, installing the Prettier plug-in in Vscode:

Create the.prettierrc.js file in the root directory of the project, which is the default pertTier configuration file:

modules.exports = {
  // Do not end with a semicolon
  "semi": true.// Use single quotes
  "singleQuote": true.// Multiline comma delimited syntax, the last line is not comma
  "trailingComma": "none"
}

Copy the code

For more configuration, see Prettier Options

In Settings, search for Save and check Format On Save:

Then add the configuration to setting.json:

"[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
},
Copy the code

Restart the Settings. Otherwise, the Settings do not take effect

Then enter some noncanonical code in the index.js file:

The above code, when saved, is automatically fixed to the standard code, which solves the following problems:

  1. Double quotation marks are used
  2. A semicolon is used at the end
  3. Indent inconsistent
  4. Multiple lines of code end with a comma

That’s it for the code formatting specification.

Iii. Code submission specifications

Git hooks are used to prevent code from being sent to the repository. These are the common hooks that keep code from being sent to the repository.

Git Hook Call time instructions
pre-applypatch git amPerform before
applypatch-msg git amPerform before
post-applypatch git amAfter performing Does not affect thegit amThe results of the
pre-commit git commitPerform before You can usegit commit --no-verifybypass
commit-msg git commitPerform before You can usegit commit --no-verifybypass
post-commit git commitAfter performing Does not affect thegit commitThe results of the
pre-merge-commit git mergePerform before You can usegit merge --no-verifyBypass.
prepare-commit-msg git commitAfter execution, before the editor opens
pre-rebase git rebasePerform before
post-checkout git checkoutorgit switchAfter performing If not used--no-checkoutParameter, then ingit cloneIt will be executed later.
post-merge git commitAfter performing In the implementationgit pull“Will also be called
pre-push git pushPerform before
pre-receive git-receive-packPerform before
update
post-receive git-receive-packAfter performing Does not affect thegit-receive-packThe results of the
post-update whengit-receive-packrightgit pushReact and update references in the repository
push-to-checkout When the git – receive – packrightgit pushReact and update references in the repository, and when a push attempts to update a branch that is currently checked outreceive.denyCurrentBranchThe configuration is set toWhen updateInstead `
pre-auto-gc git gc --autoPerform before
post-rewrite performgit commit --amendorgit rebasewhen
sendemail-validate git send-emailPerform before
fsmonitor-watchman configurationcore.fsmonitorIs set to.git/hooks/fsmonitor-watchmanor.git/hooks/fsmonitor-watchmanv2when
p4-pre-submit git-p4 submitPerform before You can usegit-p4 submit --no-verifybypass
p4-prepare-changelist git-p4 submitAfter execution, before the editor starts You can usegit-p4 submit --no-verifybypass
p4-changelist git-p4 submitExecute and editchangelist messageafter You can usegit-p4 submit --no-verifybypass
p4-post-changelist git-p4 submitAfter performing
post-index-change The index is written toread-cache.c do_write_locked_indexafter

A detailed introduction to hooks can be viewed here

Pre-commit and commit-msg:

  1. commit-msg: can be used to normalize the standard format, and you can specify if you want to reject this submission
  2. pre-commit: is called before the commit and can specify whether to reject the commit as needed
(1) Use husKY + COMMITLint to check that the submitted description complies with the specification

We use the following tools to help standardize our submission:

  1. Commitlint: Checks commit information
  2. huskyIs:git hookstool

Make sure your NPM is at least 7.x. If not, install the latest NPM:

npm install npm -g
Copy the code

Install commitlint:

npm install @commitlint/config-conventional @commitlint/cli --save-dev
Copy the code

Create the commitlint.config.js file in the root directory:

module.exports = {
  // Inheritance rules
  extends: ['@commitlint/config-conventional'].// Define the rule type
  rules: {
    // Type definition, which means git must submit a type within the following type range
    'type-enum': [
      2.'always'['feat'.// 新功能 feature
        'fix'./ / fix the bug
        'docs'.// Document comments
        'style'.// Code format (changes that do not affect code execution)
        'refactor'.// Refactoring (neither adding new features nor fixing bugs)
        'perf'.// Performance optimization
        'test'.// Add tests
        'chore'.// Changes to the build process or accessibility tools
        'revert'./ / back to back
        'build' / / packaging]],// Subject case is not checked
    'subject-case': [0]}}Copy the code

Install the husky:

npm install husky --save-dev
Copy the code

Enter the command on the console to generate the.husky folder:

npx husky install
Copy the code

(2) Use the commit-msg hook to normalize the commit message

NPX –no-install commitlint –edit “$1” : NPX –no-install commitlint –edit “$1” :

npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
Copy the code

Then test the submission:

Commit = commit = commit = commit = commit = commit = commit = commit

The code was submitted successfully, and the output log did not have any problems.

(3) Use pre-commit to detect the code specification at the time of submission

The code format specification section explains how to handle code formatting, but such a formatting problem can only be handled locally, and we need to manually configure autosave in Vscode. So that raises the question, what if some people don’t have this thing configured? What if he submits some messy code?

Therefore, we need to use pre-commit to avoid this risk. We expect husky to monitor the pre-commit hook and execute the NPM run ESLint directive under that hook to do the detection:

npx husky add .husky/pre-commit "npm run eslint"
Copy the code

Let’s modify the contents of test.js and submit it again:

The pre-commit prevented us from committing because there was non-standard code

After modifying the non-standard code, submit again:

After modification, the code is committed successfully.

(4) Use Lint-staged automatic formatting fixes

Above, we completed the standardized submission of the code. We detected some irregularities in our code in the pre-commit and blocked our submission. We could only successfully submit the code after manually repairing the non-standard code. So there are several problems with this:

  1. We only modified individual files, there is no need to check all file code formats
  2. It can only give us the corresponding error, we need to manually modify the code
  3. After modification, you need to manually manuallygit add .

Lint-staged can solve these problems by installing Lint-staged:

npm install lint-staged --save-dev
Copy the code

Add configuration to package.json:

"lint-staged": {
    "./**/*.{js}": [
        "eslint --fix"."git add"]}Copy the code

Then modify the.husky/pre-commit file:

#!/bin/sh
. "$(dirname "$0")/_/husky.sh"

npx lint-staged
Copy the code

Disable Prettier to save automatic repair (otherwise cannot test) :

Modify the test.js file to add some non-standard code:

Then commit:

This process lint-staged does two things:

  1. If the rule is met, the submission succeeds.
  2. If the rule is not met: it is executed automaticallyeslint --fixIf the fix is successful, it will help you to submit the fixed code. If it fails, it will prompt you with an error and let you fix the error before you can submit the code.

As shown, the code is fixed and test.js is committed to the staging area.

(5) Normalize the submission code with Commitizen

Having to manually enter the commit information every time is cumbersome and prone to irregularities, so we can normalize the commit code using Commitizen

Install commitizen globally, note that this is a global install, otherwise can not execute the plugin command:

npm install commitizen -g
Copy the code

Install CZ-CustomIZABLE within the project:

npm install cz-customizable --save-dev
Copy the code

Add the following configuration to package.json:

"config": {
    "commitizen": {
        "path": "./node_modules/cz-customizable"}}Copy the code

Create the.cz-config.js custom prompt file in the root directory:

module.exports = {
  // Optional type
  types: [{value: 'feat'.name: 'Feat: New Feature' },
    { value: 'fix'.name: 'fix: fix' },
    { value: 'docs'.name: 'docs: Document changes' },
    { value: 'style'.name: 'style: code format (changes that do not affect code execution)' },
    { value: 'refactor'.name: 'refactor: refactoring (neither adding features nor fixing bugs)'},
    { value: 'perf'.name: 'PERF: Performance Tuning' },
    { value: 'test'.name: 'test: add test ' },
    { value: 'chore'.name: 'chore: Changes to the Build process or accessories' },
    { value: 'revert'.name: 'revert:   回退' },
    { value: 'build'.name: 'build: package'}].// Message step
  messages: {
    type: 'Please select submission type :'.customScope: 'Please enter modification scope (optional):'.subject: 'Please briefly describe submission (required):'.body: 'Please enter detailed description (optional):'.footer: 'Please enter issue to close (optional):'.confirmCommit: 'Confirm submission using the above information? (y/n/e/h)'
  },
  // Skip the question
  skipQuestions: ['body'.'footer'].// Subject text length is 72 by default
  subjectLimit: 72
}
Copy the code

Git cz git commit

Select the corresponding type and proceed in sequence. If you need to skip, press Enter directly:

Output log, all normal:

That’s it for the code submission specification.

Four,

Standardization specification for our development process, code management is of great significance, follow the code format specification and code submission specification, is conducive to our better maintenance of code, reduce errors, reduce code conflicts and so on; Every company has its own standards, so this article takes you from zero to one to build a project that conforms to the Eslint standard and meets the contractual submission requirements from a quick build perspective. Tools such as Eslint and Prettier can be configured according to the needs of their own projects.

Five, the reference

  • Contract submission
  • Eslint
  • Prettier
  • commitlint
  • husky
  • commitizen
  • git hooks