Preface
An old project of the company , No verification before code submission , When I get it , Thinking about the old project, I don't have time to help it with these , Anyway, just change a little something ; Try to follow its code style , Submit after writing ;
Until one day , Another person joined in . good heavens , Something happened directly .
Many documents are submitted together , then commit-msg No specification , Code indentation is not standardized , Line breaks are also inconsistent , There are a lot of useless code , Poor readability ;
When you one day fetch Code , I found many files like this Are you in a state of collapse ?
But the problem has to be solved after all ; The best way to treat sewage is to start from the place where sewage can be produced . Let me add it .🥰
Now I will take you all , Through the first husky
+eslint
Complete the simplest code specification verification , And then gradually optimize , Finally through husky
+eslint
+lint-stage
+commitlint
+prettier
Achieve a strong limit . Finally, cooperate with commitizen
, adopt commitlint-config-cz
+cz-customizable
Implement customized submission templates and restriction rules to achieve the team's final Project submission restriction statute
.
eslint+prettier
Here I have adapted a set for this project eslit The rules , The code submitted according to this set of rules will not conflict .
eslint and prettier Everyone should have used it in ordinary projects , I should be familiar with , There will be no space here .( If you want to see it, you can chat with me in private , I can write a separate article eslint and prettier The theme of the article )
In this article , Mainly explain how to work in a team , stay git Before submitting code changes , Check the non-standard code and submitted information , Repair , And limit irregular submissions .
husky
The first thing to introduce is husky
, Engage in Engineering , We must all have husky
, It can easily help us stop the attack of the little ones , No , Is to add git hooks
The specific methods
First we will husky
Install into development dependencies
npm i husky -D
# or
yarn add husky -D
Be careful
The version I am currently installing is
[email protected]
, because[email protected]
And then I didbreaking change
, So in6.0.0
The method of setting hooks before version is no longer applicable , Here we only introduce the latest methods .
After the installation , We need to create one in the current project .husky
Directory and specify the directory as git hooks
directory .
Use the following command to quickly create
#--no-install Parameters indicate mandatory npx Use... In the project node_modules In the catalog husky Dependency package
npx --no-install husky install
In order to allow others to automatically create dependencies after installing them in this project .husky
Directory and specify the directory as git hooks
directory , We need to be in package.json
Add a script "prepare": "husky install"
Use the following command to quickly add
npm set-script prepare "husky install"
prepare
The script will be innpm i
Or otheryarn or yarn add
Then automatically execute . That is to say, it will be executed automatically after we install the dependencyhusky install
command , To automatically create.husky
Directory and specify the directory asgit hooks
directory .
Use the following command to quickly create
npx --no-instal husky add .husky/pre-commit "npm run [ The order you're going to execute ]"
When you're done, you can see .husky
There is a new pre-commit
file , The content is
So here I'm going to use theta npm run lint
, So we can cooperate Eslint Code verification of , To limit the submission of non-standard code
You can see , Do not conform to the Eslint The code of the verification rule cannot be submitted ;
Of course , The error reporting problem here is only caused by irregular indentation , There are quotation marks for problems like this , Sentence ending semicolon , Line breaks and so on ... Both can pass eslint
Parameters of --fix
To automatically repair , In this way, you can , First, the simple code style problems that can be automatically repaired commit. Complicated situations still need to be handled manually .
Speaking of line breaks , What we need to know here is : stay Windows On the default is carriage return (Carriage Return Line Feed, CRLF), However , stay Linux/MacOS On the other hand, it's line breaking (Line Feed, LF).
We can try to change the original newline character to crlf
The file of is formatted with a newline character of lf
after , perform git add .
The situation of .
You can see that in the end LF Line breaks are still CRLF Transformed ;
If you can't collaborate across platforms ( All in Mac/Linux, Or both Windows On collaboration ), Only need to pass in the current project git config core.autocrlf false
To prevent this from happening .
For the sake of insurance , You need to create a new .gitattributes
file ( It is mainly used to define the attributes of each file , To facilitate git Help us manage .), Set up eol(end of line) For the specified line break (lf/crlf), Here I put all the documents *.*
Line breaks of are set to LF, And some non text files are marked ( Exclude them ), You can also set the corresponding properties for each file type => *.js eol=lf
,*.ts eol=lf
...
*.* eol=lf
*.jpg -text
*.png -text
...
# perhaps
*.js eol=lf
*.ts eol=lf
*.json eol=lf
...
The contents of the document are as follows
such , No matter what platform we develop , File line breaks are unified as LF.
You can see the use of .gitattributes
Execute after configuring the file git add
, All files that do not specify line breaks will be automatically replaced with the line breaks you specify , For example, I specify here lf
, that git add .
after , Not in lf
Newline files will be converted to lf
, And output at the terminal warning: CRLF will be replaced by LF in xxxx/filename
, Pictured
.gitattributes
There are many uses , You can see gitattributes.
🥰 Come here , The simplest code style restriction method has been implemented .
Now that it's done , We must make a complete set , And easy to use . Let's continue to improve other functions ~
lint-staged
What is? lint-staged
? seeing the name of a thing one thinks of its function , This tool is only used to check git Staging area file , It's you git add file1,2,3...
Run in the staging area file after lint
A tool for .
Submit oneortwo documents at a time , But they all want lint
All documents , It's not necessary , We only need to submit the code lint
, This can reduce a lot of unnecessary time .( If you modify one file at a time , All going lint
All the files , This tool means nothing to you ,husky
Just enough )
Usage method
We will .husky/pre-commit
The code written before is changed to
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
- npm run lint
+ npx --no-install lint-staged
And then in package.json Add the following code in ,lint-staged
Object is configured in the way of key value pairs , The key name is a single file or a file type that you want to process , Multiple types can be written in {}
in , Separate with commas ; The key value is an array , In the array is lint The command group that needs to be executed .
{
"lint-staged": {
"*.{ts,js,vue}": ["eslint", "echo ' That's all right. !'"]
}
}
After adding the above code , We passed the test , Change the indentation of the two files to non-conforming , Then one of the files is temporarily stored , We run git commit
Later, it was found that the terminal was reporting an error , There is only one file lint
Error message , The error of another file did not appear .
When all staging codes meet the specification , Will be submitted through verification .
Preparing lint-staged...
Hiding unstaged changes to partially staged files...
Running tasks for staged files...
Restoring unstaged changes to partially staged files...
Cleaning up temporary files...
commitizen
Commitizen It's a composition that conforms to the above Commit Message A standard tool . Through it, we can realize the interactive writing standard Commit Message.
If only used in this warehouse
npm install commitizen -D
If you want to use it all commitizen Come and help you with commit
npm install commitizen -g
After installation , Generally, we adopt the method that conforms to Angular Of Commit message Format submission specification ( Of course, it can also be customized , I'll talk about it later ~), Run the following command to generate a match Angular Submit in standard format Commit message.
If your project uses npm
# If your project uses npm
npx --no-install commitizen init cz-conventional-changelog --save-dev --save-exact
If your project uses yarn
# If your project uses yarn
npx --no-install commitizen init cz-conventional-changelog --save-dev --save-exact
After running the above command , It will be installed for your project cz-conventional-changelog Adapter module , hold config.commitizen Add the key to the root directory of the file to package.json
in
Can be in package.json
see , The following content is automatically added
{
...
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
...
}
After completion , Through the command yarn cz
, If you are globally installed commitizen
, Then you can directly git cz
, Can be written interactively through the following commit messag And then submit
Limit commitlint
because commitizen It is not mandatory , Can still pass git commit
To submit , So we must be in no matter through cz
still git commit
Before submission , All right commit messag Conduct a verification , It is not allowed to proceed if it does not conform to the specifications commit Of
First we need to install commitlint
,commitlint/config-conventional
yarn add @commitlint/cli @commitlint/config-conventional -D
Use the following command to quickly create git hooks Of commit-msg hook
So every time commit All the time, it will be commitlint Yes commit message Do a test
npx --no-instal husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
And then we create one commitlint Configure the file to the project root directory
echo "module.exports = {extends: ['@commitlint/config-conventional']}" > commitlint.config.js
The above will be generated in the project directory commitlint.config.js
, The code is as follows , He will inherit @commitlint/config-conventional
Medium Commit message standard .("feat", "fix", "perf", "refactor"...)
module.exports = {
extends: ["@commitlint/config-conventional"],
};
Then we test at the terminal
echo 'feat: bar' | npx --no-install commitlint
If the above error occurs after you execute the above command .
Change the file to UTF-8 Format can be solved ; This problem is already in Issues in , Many people have met ( I am also ).
The easiest way is , Open the file with Notepad , Choose Save as , Then change the character code in the lower right corner of the pop-up window to UTF-8 (Windows User run echo "xxx" > xx.js
when , The document code may be UTF-16 LE), After the change , Original commitlint.config.js
Just replace the file .
After solving the above problems , Let's test it again , You can see , Not in conformity with specifications commit-msg It will cause errors , It's just commit No more , Explain our commitlint It's in effect ~
Here we are ,commit-msg The verification of has also been completed
If , You want to customize commitlint Interactive text ( no need feat,fix..., Many people like to be in commit message Add one in front emoji emoticon ), Of course .
We need to install cz-customizable
To implement custom commit message The rules , And install the corresponding commitlint-config-cz
To match the verification ( Read rules directly from customized files )
Run the following command
yarn add commitlint-config-cz cz-customizable -D
In the project root directory , Create a .cz-config.js
file , And copy cz-config-EXAMPLE.js The contents of . Then change it to the rule you want .
Of course , You can also use what I wrote :
module.exports = {
types: [
{ value: "feat", name: "feat: A new feature " },
{ value: "fix", name: "fix: Fix one Bug" },
{ value: "docs", name: "docs: Only the document is changed " },
{ value: "style", name: "style: Code style. , Format fix " },
{ value: "refactor", name: "refactor: Code refactoring , Pay attention to and feat、fix Differentiate " },
{ value: "perf", name: "perf: Code optimization , improve performance " },
{ value: "test", name: "test: test " },
{ alue: "chore", name: "chore: Change the build process or tools " },
{ value: "revert", name: "revert: Code fallback " },
{ value: "init", name: "init: Project initialization " },
{ value: "build", name: "build: Change project build or external dependencies " },
{ value: "WIP", name: "WIP: Work in progress " },
],
scopes: [],
allowTicketNumber: false,
isTicketNumberRequired: false,
ticketNumberPrefix: "TICKET-",
ticketNumberRegExp: "\\d{1,5}",
// it needs to match the value for field type. Eg.: 'fix'
/*
scopeOverrides: {
fix: [
{name: 'merge'},
{name: 'style'},
{name: 'e2eTest'},
{name: 'unitTest'}
]
},
*/
// override the messages, defaults are as follows
messages: {
type: " Choose one of your submission types :",
scope: " Select a scope ( Optional ):",
// used if allowCustomScopes is true
customScope: "Denote the SCOPE of this change:",
subject: " Brief description ( most 40 A word ):",
body: ' Long description , Use "|" Line break ( Optional ):\n',
breaking: " Non compatibility description ( Optional ):\n",
footer: " Associated closed issue, for example :#12, #34( Optional ):\n",
confirmCommit: " Be sure to submit ?",
},
allowCustomScopes: true,
allowBreakingChanges: ["feat", "fix"],
// skip any questions you want
skipQuestions: ["scope", "body", "breaking"],
// limit subject length
subjectLimit: 100,
// breaklineChar: '|', // It is supported for fields body and footer.
// footerPrefix : 'ISSUES CLOSED:'
// askForBreakingChangeFirst : true, // default is false
};
Created .cz-config.js
After the document , We need to go back to package.json In file , take config.commitizen.path Change to "node_modules/cz-customizable"
, If your .cz-config.js
The file is in the root of the project , Then you can not configure the following ,commitlint-config-cz It will automatically search under the root directory of the project : .cz-config.js
or .config/cz-config.js
...
{
"config": {
"commitizen": {
"path": "node_modules/cz-customizable"
},
// If your .cz-config.js The file is in the root of the project , Then you can not configure the following ,commitlint-config-cz It will automatically search under the root directory of the project : .cz-config.js or .config/cz-config.js
"cz-customizable": {
"config": " Your file path /xxxconfig.js"
}
}
}
...
About commitlint-config-cz
More advanced usage can be found in commitlint-config-cz
Finally, we will create the commitlint.config.js
Change the code in
module.exports = {
- extends: ["@commitlint/config-conventional"],
+ extends: ["cz"],
};
Or you can be in commitlint.config.js
Manually add custom rules in , He will cover extends The rules in the
module.exports = {
extends: ["@commitlint/config-conventional","cz"],
rules: {
"type-enum": [
2,
"always",
[
"init",
"build",
"ci",
"chore",
"docs",
"feat",
"fix",
"perf",
"refactor",
"revert",
"style",
"test",
],
],
},
};
Come here , Self defined commit message The verification of ok 了
Last
remind : The code style and rules of the project should be formulated with the team ~
thus , In the project of team collaboration , Submissions that do not meet the specifications are strangled in the cradle . All of us, whether writing code or submitting code, had better be standardized ~ Don't make trouble for yourself at the same time , It will not cause trouble to others or the company . This is the whole content of this article ~ If it helps you , Remember to praise and encourage ~
I'm Rongding , A front-end development for happy programming 🥰
If you also love front-end technology ! Scan QR code ~ Join the front-end Superman technology exchange group
reply [ Add group ], Will pull you into the learning exchange group , Make progress with other front-end enthusiasts !
reply [ Books ], Get a lot of front ends pdf Books .
The circle of friends holds book delivery activities from time to time . Come on together , blunt !