- 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:
commitlint
: Used to detect submitted informationlint-staged
: Check the updated code for this modification, and fix it automatically and can be added to the staging areapre-commit
:git hooks
Check code compliance before submitting it. Non-compliance will not be submittedcommit-msg
:git hooks
Hooks are checked before code is submittedcommit
Whether the information conforms to the specificationcommitizen
:git
A standardized submission tool to help you fill outcommit
Information, 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:
- Double quotation marks are used
- A semicolon is used at the end
- Indent inconsistent
- 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 am Perform before |
|
applypatch-msg | git am Perform before |
|
post-applypatch | git am After performing |
Does not affect thegit am The results of the |
pre-commit | git commit Perform before |
You can usegit commit --no-verify bypass |
commit-msg | git commit Perform before |
You can usegit commit --no-verify bypass |
post-commit | git commit After performing |
Does not affect thegit commit The results of the |
pre-merge-commit | git merge Perform before |
You can usegit merge --no-verify Bypass. |
prepare-commit-msg | git commit After execution, before the editor opens |
|
pre-rebase | git rebase Perform before |
|
post-checkout | git checkout orgit switch After performing |
If not used--no-checkout Parameter, then ingit clone It will be executed later. |
post-merge | git commit After performing |
In the implementationgit pull “Will also be called |
pre-push | git push Perform before |
|
pre-receive | git-receive-pack Perform before |
|
update | ||
post-receive | git-receive-pack After performing |
Does not affect thegit-receive-pack The results of the |
post-update | whengit-receive-pack rightgit push React and update references in the repository |
|
push-to-checkout | When the git – receive – packright git pushReact and update references in the repository, and when a push attempts to update a branch that is currently checked out receive.denyCurrentBranchThe configuration is set to When updateInstead ` |
|
pre-auto-gc | git gc --auto Perform before |
|
post-rewrite | performgit commit --amend orgit rebase when |
|
sendemail-validate | git send-email Perform before |
|
fsmonitor-watchman | configurationcore.fsmonitor Is set to.git/hooks/fsmonitor-watchman or.git/hooks/fsmonitor-watchmanv2 when |
|
p4-pre-submit | git-p4 submit Perform before |
You can usegit-p4 submit --no-verify bypass |
p4-prepare-changelist | git-p4 submit After execution, before the editor starts |
You can usegit-p4 submit --no-verify bypass |
p4-changelist | git-p4 submit Execute and editchangelist message after |
You can usegit-p4 submit --no-verify bypass |
p4-post-changelist | git-p4 submit After performing |
|
post-index-change | The index is written toread-cache.c do_write_locked_index after |
A detailed introduction to hooks can be viewed here
Pre-commit and commit-msg:
commit-msg
: can be used to normalize the standard format, and you can specify if you want to reject this submissionpre-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:
- Commitlint: Checks commit information
- huskyIs:
git hooks
tool
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:
- We only modified individual files, there is no need to check all file code formats
- It can only give us the corresponding error, we need to manually modify the code
- After modification, you need to manually manually
git 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:
- If the rule is met, the submission succeeds.
- If the rule is not met: it is executed automatically
eslint --fix
If 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