preface
The vast majority of projects in daily development are conducted by teams. However, due to the different code habits and coding differences of each member, the code of the whole project will eventually be uneven and various styles of code will appear.
This difference will seriously lead to low efficiency of team collaboration, and the later maintainability will be seriously reduced. For example, indenting code, most of which is based on two or four Spaces, can be very cumbersome to iterate without formatting tools. You can only add or remove Spaces line by line, which is a waste of time and meaningless.
Therefore, it is important to develop a uniform code style and configure formatting tools accordingly, and it is best to solve this problem in development, detect errors before the code is run, and ensure that the code pushed to the remote side is very standardized.
This article will be based on the vuecli3 scaffolding project, using vscode as the code editor, step by step to configure the relevant plug-in from scratch, and finally achieve automatic code formatting error repair when saving, you will learn along with this article.
vscode
The editorVetur
The main functions of the plug-in, a variety of configurationsvue
Snippets of code- To solve
ESLint
theautofix
withprettier
Formatting conflicts between understandeslint-config-prettier
witheslint-plugin-prettier
The difference between - How to access formatting tools for old scaffold projects
- Automatically formats and normalizes the commit log when code is submitted
git hook
toolhusky
Version byv4
The migration tov7
“, how do I modify related configuration items
If you’re focused on how to use it and not on the configuration flow and steps, you can skip and browse the summary sections of each chapter, or you can visit the Github repository.
The preparatory work
Tool version
Please make sure that you have the VScode editor and Node environment installed, and that you have installed vuecli scaffolding and git tools globally.
vscode
1.612.
node --version
v1415.. 0
vue --version
@vue/cli 4.53.
git --version
git version 2.27. 0.windows1.
Copy the code
Vuecli3 function selection
Select a directory or folder and start creating vuecli scaffolding. For details, see Vuecli. Note that it is best to start Powershell to create scaffolding.
In the root directory of the disk, hold down Shift and right click to open the Powershell window.
Run the vue create app command and select Manually select features to Manually set more options.
Press up or down to switch options, Enter to confirm, and space to select or cancel
Only Vue version and Babel translator are selected for project functionality.
The vUE version is 2.x, and all configurations are stored in an independent file.
The creation succeeds.
Vscode initial plug-in
Vscode plug-ins can only be installed in Chinese and Reload. Chinese language extension plug-ins can be installed or not.
If you have other plug-ins installed, you can disable them and do not need to uninstall them to ensure that the configuration is correct
The Reload plug-in will add a Reload button in the status bar at the bottom right corner of the vscode editor to Reload the vscode window quickly for easy debugging.
Type Shift + Ctrl + P and type settings.json to open the Settings. In order not to affect the debugging effect, it is best to comment out your personalization and other Settings.
Repair process
Vetur code style/jsconfig.json
When vscode opens the vuecli3 scaffold, it is obvious that app. vue is full of text fonts without highlighting, and the code spacing is very tight, which is very ugly.
So the visual code highlighting problem needs to be solved first, so search for and install the Vetur plug-in in vscode.
If you don’t get it, click the Reload button on the status bar and you’ll get it within a few seconds.
The reason for this is that Vetur will preferentially look for tsconfig.json and jsconfig.json files in the project. If none is present, Vetur will look for vetur.config.js, and if none is present, Vetur will throw this warning.
Although the warning effect is not big, but there is no like me to look at the anger, is really angry obsessive compulsive disorder.
No, just create a jsconfig.json.
// jsconfig.json
{
"compilerOptions": {
"baseUrl": ". /"."paths": {
"@ / *": ["src/*"]}},"exclude": ["node_modules"."dist"]}Copy the code
If jsconfig.json is present in the directory, it indicates that the directory is the root of the JavaScript project. Therefore, the directory containing the following files is considered the root directory.
├ ─ ─ node_modules ├ ─ ─... ├ ─ ─ jsconfig. Json ├ ─ ─... ├ ─ ─ package. Json ├ ─ ─ the README, mdCopy the code
Exclude is used to tell vscode which files are not source code, keeping IntelliSense at a high performance level. BaseUrl is used to specify the base directory, and Paths represents the path map computed relative to the baseUrl option.
So @/* is a file or folder mapped to the SRC directory under the current directory app. If you still don’t understand, you can look at the following image. After typing @/, the intelligent prompt will show the files or folders in the SRC directory. This smart tip is the result of the work you just did to configure jsconfig.json.
Try commenting jsconfig.json, Reload the window, and type @/ again to see if there is an intelligent prompt
The code looks a lot more comfortable when highlighted, but a little more compact, so change the bottom line spacing and Tab Spaces.
Create a. Vscode folder in the root directory and add settings.json. LineHeight is used to specify the lineHeight, and tabSize is used to specify a Tab key for several Spaces, but may be overwritten.
The reason is because editor.detectIndentation is turned on by default, which means that editor.tabSize is automatically detected based on the file contents, and the Settings are automatically overwritten if editor.tabSize is detected. So to force a Tab key to be several Spaces, set editor.detecIndentation to false.
// .vscode/settings.json
{
"editor.tabSize": 2."editor.lineHeight": 24
// "editor.detectIndentation": false
}
Copy the code
Modify the style of app. vue.
ESLint error checking
,
However, since the essential rule set is limited, the official recommended Vue /recommended rule set is now selected to validate the code, so the Vetur rule set will be customized, as described below for custom error checking.
First, turn off Vetur’s template validation.
// .vscode/settings.json{..."vetur.validation.template": false
}
Copy the code
Template validation has been disabled.
Then install the ESLint plugin for vscode and let the ESLint plugin check for errors instead of Vetur.
The ESLint plugin will use the ESLint dependencies in the project. If they are not provided in the project, the ESLint plugin will look for them globally, so the project will need to install the ESLint dependencies. For VUE projects, a set of rules for checking vUE code is necessary, which can be provided by eslint-plugin-Vue.
npm i eslint eslint-plugin-vue -D
Copy the code
Eslint-plugin-vue has multiple rule sets, and ESLint doesn’t know which rule set to use, so it has to tell ESLint which rule set to use to check code, so create a.eslintrc.js file in the root directory.
// .eslintrc.js
module.exports = {
root: true.extends: [
'plugin:vue/recommended'].rules: {
quotes: ['error'.'single']}}Copy the code
The steps for ESLint to detect configuration files are as follows, for more details.
- In-project lookup
.eslintrc.*
orpackage.json
File (package.json
Related attributes can also be configured in) - If no, search for the disk in the parent directory until the root directory
- If found in the above two steps
root: true
, stops the search in the parent directory
Also extends means that a vue/recommended rule set is enabled, check rules can be customized in rules, and [‘error’, ‘single’] means that strings can only be single quotes, and if they are not single quotes are highlighted with an error underscore.
[‘warn’, ‘single’] will be highlighted with a warning underscore
Added configuration click status bar Reload window, view app. vue file, custom error checking has taken effect.
Autofix
Now that you’re ready to examine the code, try fixing it manually.
But you can browse through component/HelloWorld.vue and get an entire warning asking if you’re in a panic. Like app. vue code is less, can be manually fixed, but HelloWorld. Vue should not be changed line by line.
Is it possible for ESLint to detect code and fix it? ESLint has an autofix feature.
Return app.vue to the following state.
Vscode command line run the following command to fix app.vue.
npx eslint src/App.vue --fix
Copy the code
Fixed app.vue.
The console outputs two errors: the element v-for requires a key, and the item is declared but not used. Keep in mind that ESLint can only fix simple errors, such as v-for key issues that you need to fix manually.
You may be asking if you have to execute NPX esLint for a file every time you write code… If so, it would be a real embarrassment.
Add the following command to settings.json to automatically fix the file every time it is saved.
You may see source.fixAll in other articles, but the difference is source.fixAll means automatic repair is enabled for all plug-ins, source. fixall. eslint means only in ESLint
// .vscode/settings.json{..."editor.codeActionsOnSave": {
"source.fixAll.eslint": true}}Copy the code
App.vue when saved.
Prettier formatting
So the problem is solved? It doesn’t. Look at the following.
Because of the rule vue/html-indent in the rule set vue/recommended provided in eslint-plugin-vue, this rule enforces consistent indentation for tags, so
automatically fixes indentation when saved.
But there is no fix in
// .eslintrc.js
module.exports = {
....
rules: {...'vue/script-indent': ['error'.2, {
'baseIndent': 0.'switchCase': 0.'ignores': []}},'overrides': [{'files': ['*.vue'].'rules': {
'indent': 'off'}}}]Copy the code
However, this approach is not recommended because it is time consuming, rule coverage is not complete (some rules may be missing), and it is not necessary. The definitions of configuration items are not described here. For more details, see.
For an interesting operation, you can right-click on app. vue and select Format (Shift + Alt + F), then save (Ctrl + S), and you will find that the code in < Template > and
Why was it fixed? The reason is that formatting documents is provided by Vetur, which by default comes bundled with formatters (like Prettier) to format code.
What you should understand is that code rules fall into two categories, code quality rules and code style rules. Problems with code quality mean that the project may not work, or there may be potential defects. The code style is different, the code style is wrong, just the code is ugly, you don’t like it.
Code quality rules.
- No-unused-vars: disables unused variables
- No-use-before-define: Disallows the use of a variable before it is defined
- no-v-html: Prohibited
v-html
To preventXSS
attack .
Code style rules.
- Max-len: indicates the maximum length of a single line
- Semi: Forces or forbids the use of semicolons
- Indent: indent problem
.
While we know that the vue/recommended rule set currently used by ESLint only includes checks for code quality (v-for key issues, etc.) and code style (a few, including indentation rules, such as not including maximum line length, etc.) in
, But it lacks code style verification (indentation rules, etc.) in
For indentation of both
and
Vetur is opened Vetur useWorkspaceDependencies is true, that it can use priority under the root directory of prettier formatting depend on the package, so to customize Vetur formatting functions.
npm i prettier -D
Copy the code
Add. Prettierrc.js, add simple rules printWidth (maximum number of newlines per line), semi (semicolon at end of statement), arrowParens (omit parentheses around arrow function when it is a single argument).
// .prettierrc.js
module.exports = {
semi: false.printWidth: 110.arrowParens: 'avoid'
}
Copy the code
After formatting the document and saving it, you can see that the indentation in
FormatOnSave
No, is it possible to save and fix automatically like ESLint? The answer is yes.
// .vscode/settings.json{..."editor.formatOnSave": true,}Copy the code
Now restore the code to try to save (Crtl + S).
But something unexpected happens, when you save, you start with ESLint’s autofix and then run Vetur formatting, meaning that the autofix is before Vetur formatting.
As a result, prettier is used (for example, double quotes for strings), which obviously doesn’t conform to ESLint’s rules. So the format is fixed, but ESLint detects errors.
So that the frequent saving will flash frequently.
Resolve the conflict between ESLint and Prettier
eslint-config-prettier
The root cause of frequent flickering is that esLint conflicts with prettier when used together. While prettier formats double quotes by default, esLint considers strings to be single quotes, so prettier formats double quotes by adding the following rule to.prettierrc.js
// .prettierrc.js
module.exports = {
...
singleQuote: true
}
Copy the code
Prettier prettier thinks a line can be wrapped when its maximum length is 110, while ESLint thinks everything should start on another line.
Note that the actual code formatting issues have already been resolved (such as indent issues, maximum line length, etc.), and you might wonder if the problem would be solved if esLint’s vue/ max-Attributes-per-line rules were disabled without it checking for warnings.
Heh heh, yes, you guessed it, it is true.
But we don’t have to, eslint-config-prettier already does, as the name probably tells us, config in between esLint and Prettier, used to balance configuration between esLint and Prettier.
npm i eslint-config-prettier -D
Copy the code
But what configuration is used to balance? The official documentation gives the answer by turning off all rules in ESLint that aren’t necessary or would conflict with Prettier, which are actually code style rules.
Adding prettier to.eslintrc.js enables eslint-config-prettier, where the previous rule of the same kind is overwritten because it might not take effect.
// .eslintrc.js
module.exports = {
...
extends: [
'plugin:vue/recommended'.'prettier']}Copy the code
When saved, you can also see that esLint-related code quality rules are not disabled.
eslint-plugin-prettier
Remember when the
label was indented incorrectly, the yellow warning was highlighted with a wavy line.
If you still want to include this functionality, install the recommended optional plugin eslint-plugin-Prettier.
Prettier already does prettier because the plugin eslint-config-Prettier already does Prettier, and esLint does not report formatting errors because esLint-config-Prettier is disabled.
What does eslint-plugin-prettier do? It converts the rule for prettier’s format problem into its esLint counterpart, so esLint will report formatting errors in code where the prettier format problem exists.
npm i eslint-plugin-prettier -D
Copy the code
Eslintrc.js, where plugins refer to registering prettier as a plug-in, prettier/pretiier refer to injecting the rule provided by the prettier plug-in into ESLint and making it run prettier in ESLint.
module.exports = {
root: true.extends: ['plugin:vue/recommended'.'prettier'].plugins: ['prettier'].rules: {
quotes: ['error'.'single'].'prettier/prettier': 'error',}}Copy the code
There are two rules that don’t apply.
- Arrow-body-style: The body of an arrow function must be curly braces only
const foo = () = > { return 0 } // OK
const foo = () = > 0 // ERROR
Copy the code
- Prefer-arrow-callback: use arrows as callback functions
foo(arg= > {}) // OK
foo(function(arg) {}) // ERROR
Copy the code
Obviously none of this makes sense, and the arrow-body-style rule code will not be elegant enough to modify.eslintrc.js.
// .eslintrc.js
module.exports = {
root: true.extends: ['plugin:vue/recommended'.'prettier'].plugins: ['prettier'].rules: {
quotes: ['error'.'single'].'prettier/prettier': 'error'.'arrow-body-style': 'off'.'prefer-arrow-callback': 'off',}}Copy the code
The above configuration can be easily combined into the following. For more information, please refer to the official documents.
// .eslintrc.js
module.exports = {
root: true.extends: ['plugin:vue/recommended'.'plugin:prettier/recommended'].rules: {
quotes: ['error'.'single',}}Copy the code
After the above configuration is complete, your app. vue or helloword. vue etc will have a lot of errors.
.prettierrc.js adds rule for.prettierrc.js because of a line break at the end of a line
// .prettierrc.js
module.exports = {
...
endOfLine: 'crlf'
}
Copy the code
At this point, all the formatting steps are complete.
The difference between different
Eslint-config-prettier not only provides the formatting rule for Prettier, but also disables all rules in ESLint that are unnecessary or would conflict with Prettier.
Eslint is responsible for code quality checking, no code format checking. Code quality fixes rely on ESLint’s autofix, and code format fixes rely on Prettier.
When esLint-config-prettier is installed, esLint’s autofix and prettier’s save formatting must be turned on at the same time as prettier’s formatting.
// .vscode/settings.json{..."editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"editor.formatOnSave": true,}Copy the code
When only esLint autofix is enabled, it is obvious that only code quality has been fixed, not code format.
Formatting only Prettier is turned on, code quality is not repaired, code formats are repaired.
Eslint-plugin-prettier converts the rule for prettier into the corresponding ESLint rule and inserts it into ESLint.
Code quality is checked by ESLint, the rules for code quality are written by ESLint and ESlint-plugin-Vue, the rules for code format are written by Prettier, Rely on eslint-plugin-prettier conversion and inject it into ESLint.
One other thing esLint-plugin-Prettier does is run Prettier immediately after ESLint’s autofix, so the quality and format fixes can be done simply by turning on ESLint’s autofix.
Prettier does not use esLint-plugin-prettier as an autofix, but prettier does not use esLint-plugin-prettier as an autofix.
Only autofixes for ESLint are enabled, code quality and format are highlighted, and are fixed when saved.
Formatting only Prettier is turned on, code quality and format are highlighted, but only formatting is fixed.
summary
The initial scaffolding code is all text fonts, with Vetur highlighting introduced.
Vetur looks for files such as jsconfig.json in the project and throws a warning to create jsconfig.json.
// jsconfig.json
{
"compilerOptions": {
"baseUrl": ". /"."paths": {
"@ / *": ["src/*"]}},"exclude": ["node_modules"."dist"]}Copy the code
Where ESLint and ESlint-plugin-vue are used for error checking, eslint-plugin-vue is used for formatting code, Eslint-config-prettier Solves the conflict between ESLint and Prettier. The optional eslint-plugin-prettier plug-in injects the prettier formatting rule into ESLint.
npm i eslint eslint-plugin-vue prettier eslint-config-prettier eslint-plugin-prettier -D
Copy the code
Create.eslintrc.js and enable the Vue rule set for eslint-plugin-vue, eslint-config-prettier, and eslint-config-Prettier injection rule.
// .eslintrc.js
module.exports = {
root: true.extends: ['plugin:vue/recommended'.'plugin:prettier/recommended'].rules: {
quotes: ['error'.'single',}}Copy the code
Create.prettierrc.js, unify the partial formatting rule and newline character, etc.
// .prettierrc.js
module.exports = {
semi: false.printWidth: 110.arrowParens: 'avoid'.singleQuote: true.endOfLine: 'crlf'
}
Copy the code
Create settings.json and save esLint’s autofix and prettier formatting automatically.
// .vscode/settings.json
{
"editor.tabSize": 2."editor.lineHeight": 24."vetur.validation.template": false."editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"editor.formatOnSave": true,}Copy the code
The role of the above plug-ins and dependencies.
- Vetur:
vscode
Plug-in for highlightingVue
Code, provides code error check and formatting, automatic code completion tips - ESLint:
vscode
Plug-ins that depend on local workspace or globaleslint
Depend on the package - eslint: Used to detect and repair code errors, custom detection rules, introduced
vue
The set of rules for code inspection - eslint-plugin-vue: Provides for detection
vue2
The rule set of codevue/recommended - Prettier: Formatting code, customizing formatting rules
- eslint-config-prettier: Used to solve
eslint
andprettier
Conflicts in code format, disabledeslint
All that is unnecessary or may have to do withprettier
Rules of conflict - eslint-plugin-prettierWill:
prettier
Code format rules in theeslint
Rules and injection intoeslint
To makeeslint
Ability to detect code formatting problems. In addition toeslint
In the implementationautofix
After the operationprettier
Git hook
Many plug-ins are introduced to standardize or fix the code during development, but they are all based on the vscode editor, and if other members are using other editors such as webstorm, then all the work is wasted.
The editor can’t completely standardize the code, but it can unify the code when it is submitted.
Git hooks are the scripts that trigger certain events (similar to the life cycle of a vue). The.git/hooks directory contains many sample scripts (which end with.sample). The sample suffix can be enabled.
Common hooks include pre-commit and commit-msg.
pre-commit
: Triggered before the file in the staging is committed, or before yougit commit ...
Before triggering. If this hook exits with a non-zero value,git
This submission will be abandoned (availablegit commit --no-verify
Skip), you can generally use this hook to check code style, etccommit-msg
: After entering the submission instructions andpre-commit
After the trigger. If this hook exits with a non-zero value,git
Submissions are also discarded, generally used to verify compliance with the specification
Husky(V4) and Lint-staged specification code
The idea should be clear: when code commits, trigger the corresponding hook to detect and standardize the code, so initialize a Git repository first.
git init
Copy the code
After installing version V4 (v4.3.8 and earlier), husky generates all types of Git hooks in the. Git /hooks directory by default. Husky then calls a script generated by Husky at each stage of git’s work, in which husky checks to see if the user is configured with the hook, runs the user-configured command if it is, and continues to execute if it is not.
npm i husky@4.38. -D
Copy the code
After installation, the directory.git/hooks spawn a number of hooks.
To test husky, create.huskyrc.json, where the pre-commit hook is triggered to run echo Hello Husky.
// .huskyrc.json
{
"hooks": {
"pre-commit": "echo hello husky"}}Copy the code
Modify the code and commit.
Now that you can trigger hooks on commit, consider whether to standardize all code in the directory before committing, or just code in the staging. It is obvious that only the code in staging can be regulated, not only to avoid reviewing the entire project, but also to avoid making changes to other files.
Plugins lint-staged perform checks on files that are temporarily stored.
npm i lint-staged -D
Copy the code
Create.lintstagedrc. Json, note that the source code is usually located in the SRC directory, so just run eslint –fix for js and vue files in the SRC directory, and then run git add temporary save after fixing the format.
// .lintstagedrc.json
{
"src/**/*.{js,vue}": [
"eslint --fix"."git add"]}Copy the code
Modify. Huskyrc. json, that is, the command in. Lintstagedrc.json will run when the pre-commit hook is triggered.
// .huskyrc.json
{
"hooks": {
"pre-commit": "lint-staged"}}Copy the code
Turning off formatting of ESLint autofix and Prettier, shuffling code styles in app. vue, storing them temporarily and committing them, you can see lint-staged tests and fixes for App.vue during pre-commit.
Commitlint specifications submit instructions
Install CommitLint/CLI and general configuration.
npm i @commitlint/cli @commitlint/config-conventional -D
Copy the code
Add commitlint.config.js to introduce the commit specification set.
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional']}Copy the code
Json, that is, when the commit- MSG hook is triggered, the corresponding command will be run.
// .huskyrc.json
{
"hooks": {
"pre-commit": "lint-staged"."commit-msg": "commitlint -E HUSKY_GIT_PARAMS"}}Copy the code
Hold and commit again, and you can see that the commitLint validates the commit instructions when the commit-msg hook fires.
Husky V4 migrates v7
The v4 version of Husky will generate all types of Git hooks. The advantage of husky is that it will work no matter what type of Git hook you set up. However, the downside is obvious. That is, the user does not set up any Git hooks, and Husky adds all types of Git hooks to Git.
The root cause of the bug in version V4 is that any complete Git hook function requires a. Git /hooks hook and a. Huskyrc. json file or package.json in the root directory. But the authors didn’t have a good way to synchronize them.
Fortunately, git 2.9 introduced core.hooksPath, which specifies the directory where the Git hook is located. When husky enables git hooks, it will specify the directory of the git hook as.husky. This way, you can add any hooks you want to the.husky folder.
Now that you have migrated from V4 to V7, uninstall husky(V4) in the directory.
npm un husky
Copy the code
Then install the latest version of Husky (currently V7.0.4).
npm i husky -D
Copy the code
Enable git hooks.
npx husky install
Copy the code
When enabled, a.husky folder is generated in the root directory, which by default includes the _ folder,.gitignore, and husky.sh.
In the meantime, the following properties will be added to the. Git /config file.
// .git/config
[core]
...
hooksPath = .husky
Copy the code
Create a new pre-commit file in the. Husky directory, where –no-install means force NPX to use the local module, do not download the remote module, but an error will be reported if the local module does not exist.
// .husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
echo 'husky > pre-commit'
npx --no-install lint-staged
Copy the code
The same is true for the migration of validation commit instructions, creating a new commit-msg hook under.husky.
// .husky/commit-msg
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
echo 'husky > commit-msg'
npx --no-install commitlint --edit $1
Copy the code
Huskyrc. json in the root directory can also be removed, because v7 does not rely on this layer of mapping. The hook in the.husky directory will run commands directly. This is the advantage of v7.
summary
Husky v4 version
Since you are using Git to manage your code, make sure your project has been initialized as a Git repository.
git init
Copy the code
Git hook installation: HusKY for adding hooks to Git, Lint-staged for checking files in temporary storage, and Commitlint for checking commit instructions Config-conventional Is used to provide check rule sets.
npm i husky@4.38. lint-staged @commitlint/cli @commitlint/config-conventional -D
Copy the code
Create.lintStagedrC.json to repair temporary files.
// .lintstagedrc.json
{
"src/**/*.{js,vue}": [
"eslint --fix"."git add"]}Copy the code
Create commitlint.config.js and enable the config-Conventional rule set.
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional']}Copy the code
Create a new.huskyrc.json and execute the command when the Git hook is triggered.
// .huskyrc.json
{
"hooks": {
"pre-commit": "lint-staged"."commit-msg": "commitlint -E HUSKY_GIT_PARAMS"}}Copy the code
Husky v7
V4 Migrate V7 Uninstall HUSKY (V4).
npm un husky
Copy the code
Install the latest version of Husky (currently V7.0.4).
npm i husky -D
Copy the code
Enable git hooks.
npx husky intall
Copy the code
Create pre-commit and commit-msg hooks.
// .husky/pre-commit
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
echo 'husky > pre-commit'
npx --no-install lint-staged
// .husky/commit-msg
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
echo 'husky > commit-msg'
npx --no-install commitlint --edit $1
Copy the code
Then delete the. Huskyrc. json file.
The plug-in
The functions of the above plug-ins.
- husky: in order to
git
Client Addhook
Tools,v4
(v4.3.8
And previous versions) will be available in.git/hooks
To inject all types ofhook
And thev7
Version will specifygit hook
Directory for.husky
- Lint-staged commands only for files provisionally stored to improve efficiency
- @commitlint/cli: Used to check submission instructions
- Commitlint/config-Conventional: provides the rule set for checking and submitting instructions
Q&A
How to turn off or skip ESLint validation rules?
Some projects do not apply esLint’s rule set very well, for example vue/recommended rule set vue/ no-V-html disables V-HTML directives, but sometimes uses V-HTML as a last resort.
The first way is to turn this rule off in.eslintrc.js.
// .eslintrc.js
module.exports = {
...
rules: {...'vue/no-v-html': 'off',}}Copy the code
There are three alarm levels: 0/ OFF indicates that faults are ignored, 1/ WARN indicates that faults are warned, and 2/error indicates that faults are reported
The second way is to use the vue/comment-directive rule, which uses comments to skip one or more lines of validation.
Comments supported by this rule include.
eslint-disable
: Disable verificationeslint-enable
: Enable verification and matcheslint-disabled
Multi-line verification can be disabledeslint-disable-line
: Disables current line verificationeslint-disable-next-line
: Disables the next line verification
Turn off multi-line validation, where V-HTML validation on lines 6 and 7 is skipped.
Closes the verification of the current line, where the semicolon verification at the end of the statement in line 32 has been skipped.
Disable the next line verification.
Note that the above comment will disable all ESLint validation rules. It is recommended to add the disabled rule name after the comment, for more details.
How to access formatting tools for old projects?
Old projects often have problems with the source file format, but it is not possible to manually fix every file by going to Ctrl + S. You can add commands in package.json to fix the source file within SRC.
This is not recommended, however, as formatting can cause potential problems. If you have a small number of source files and can guarantee full testing, you can do this. However, there are many source files, it is recommended to format only the files you modify, the rest of the irrelevant files or do not move.
// package.json{..."scripts": {..."eslint:fix": "eslint src/**/*.js src/**/*.vue --fix"}}Copy the code
Note that esLint :fix only fixes simple errors, other cases, such as the component props default, still need to be fixed manually
How to repair a file that cannot be formatted?
Some files cannot be formatted and blink frequently.
In this case, it is best to run eslint’s fix function for a file. If there are many files, it is recommended to run the NPM run eslint:fix command.
npx eslint src/main.js --fix
Copy the code
How to skip lint phase when committing?
Git commit -m Commit can be very time-consuming, so you can skip lint-staged and Commitlint stages by executing the following commands.
However, it is recommended not to do this, because you cannot guarantee that the code submitted to the remote side is perfectly normal.
git commit -m 'xxx' --no-verify
Copy the code
How do I configure vUE snippets?
Vetur provides snippets of code to improve development efficiency.
Vue. Json file in VScode
In VSCode, type Shift + Ctrl + P, enter SNppets, and select Configure user code snippets.
Then type vue and select vue.json.
Delete all comments and add the following.
// vue.json
{
"Vue Component": {
"prefix": "cpt"."body": [
"<template>"."$1"."</template>".""."<script>"."export default {".""."}"."</script>".""."<style>".""."</style>"]."description": "Vue Component Template"}}Copy the code
Vue single file input CPT, the code snippet has taken effect.
This configuration works in vscode and works in any project, but is cumbersome to configure and needs to be added line by line in vue.json.
Project-level templates
The vscode directory structure is as follows.
├ ─ ─. Vscode │ ├ ─ ─ Settings. The json │ ├ ─ ─ vetur │ │ ├ ─ ─ snippets │ │ │ ├ ─ ─ the template. The vueCopy the code
You can add the template.vue file under the Snippets folder.
// .vscode/vetur/snippets/template.vue
<template>
<div>The ${0}</div>
</template>
Copy the code
After the vue file is added in this mode, Reload takes effect. Compared with the vue. Json file, only a single file can be set in this mode.
The vscode plug-in directory
Vscode type Shift + Ctrl + P, type Extensions Folder, and select open the extension folder.
Open the octref. Vetur – xx. Xx. Xx directory, enter the server/dist/veturSnippets folder.
Add custom code snippets or copy default.vue and modify it.
// veturSnippets/page.vue
<template>
${0}
</template>
<script>
export default {
name:' '
}
</script>
<style>
</style>
Copy the code
Reload Takes effect after an overload.
🎉 is at the end
🍻 fellows, if you have seen this article and think it is helpful to you, please like 👍 or Star ✨ to support it!
Manual code word, if there is an error, welcome to the comment area correction 💬~
Your support is my biggest motivation to update 💪~
GitHub, Blog, nuggets, CSDN synchronous updates, welcome to pay attention to 😉~