Install and configure ESLint and prettier
Eslint is a tool that performs rule-based code checks, which can be statically analyzed and reported during the coding phase. With some plug-ins, problems can be exposed in advance, given hints, and fixed, greatly reducing the number of bugs in the execution process.
Prettier prettier is a code formatting tool that formats code according to a set of rules. Using the same rules throughout the team development process ensures consistency in the final code and avoids code conflicts.
First, install and configure the esLint and Prettier tools
Install and configure ESLint
-
Install esLint dependencies
{ "devDependencies": { "babel-eslint": "^ 10.1.0"."eslint": "^ 7.32.0"."eslint-plugin-html": "^ 6.2.0"."eslint-plugin-import": "^ 2.23.4"."eslint-plugin-node": "^ 11.1.0"."eslint-plugin-promise": "^ 5.1.0"."eslint-plugin-vue": "^ 7.15.1"."vue-eslint-parser": "^ 7.10.0"}}Copy the code
-
Eslint: The core code for ESLint
-
Babel-eslint: esLint integrates with Babel
-
Eslint-plugin-vue: Integration package for ESLint and vue
-
-
Configure the ESLint rules, create the.eslintrc.js file in the root directory, and add the rules
module.exports = { /** * By default, ESLint will look for configuration files in all parent directories up to the root directory. * To restrict ESLint to a specific project, set root: true; * ESLint will stop looking in the parent directory once it finds root: true in the configuration file. * / root: true.// Specify the parser // babel-eslint: a wrapper around the Babel parser to make it compatible with ESLint. // parser: 'babel-eslint', // Setting the parser helps ESLint determine what a parsing error is. parser: 'vue-eslint-parser'.parserOptions: { parser: "babel-eslint".// Specify the js version. Syntax support ecmaVersion: 6.sourceType: "module".allowImportExportEverywhere: true,},// Additional global variables accessed by the script during execution // globals: {}, // env: specifies the running environment of the script env: { // An environment defines a set of predefined global variables. browser: true.// Es6 syntax support is automatically enabled. es6: true.node: true,},// Use third-party plugins. Globally installed ESLint instances can only use globally installed ESLint plug-ins. Local same, do not support mixing. plugins: ["html"."vue"].// The configuration file inherits enabled rules from the base configuration. /** * ESLint :recommended enables core rules marked as √ in the rules page. * / extends: [ Plugin :(no Spaces here) package name/configuration name. Plugin is parsed to eslint-plugin-vue. If parsing fails with whitespace, eslint-plugin-vue. // plugin can omit the package name prefix eslint-plugin- 'plugin:vue/essential'.'eslint:recommended']./** * Each rule has [3] error levels. * off or 0: disables the rule. Warn or 1: opens the rule. Warning level errors will not cause the program to exit. * error or 2: opens the rule, uses the error level error, when triggered, the program will exit. * / rules: { / [* * * = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Possible Errors = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =] * these rules and possible errors in JavaScript code or logic errors. * / // Forces the calculator in the "for" loop to move in the correct direction "for-direction": 2.// Disallow duplicate arguments in function definitions "no-dupe-args": 2.Disallow duplicate keys in object literals "no-dupe-keys": 2.// Disallow duplicate case tags "no-duplicate-case": 2./ / disable the console "no-console": 1.// 'no-console': process.env.NODE_ENV === 'production' ? 'error': 'off', 'no-debugger': process.env.node_env === 'production'? 'error': 'off', 'no-console': process.env.NODE_ENV === 'production' ? 'error': 'off', */ / /...}};Copy the code
If there are files that need to be ignored, you can also configure them in the.eslintignore file:
build/*.js src/assets public dist Copy the code
Install the prettier
Prettier is a code formatting tool, but is not aimed at a kind of language, to HTML/CSS/JavaScript/Vue/SCSS have effect. You can use configuration files to unify code formatting across projects to fix the problem of formatting differently between different editors/ides.
-
Install dependencies
npm i -D prettier eslint-plugin-prettier eslint-config-prettier prettier-eslint-cli Copy the code
-
Prettier: The core code for the prettier plug-in
-
Eslint-plugin-prettier: The use of prettier as the ESLint specification
-
Eslint-config-prettier: Resolves the conflict between the style specification in ESLint and the style specification in Prettier by taking the style specification of Prettier as the standard
-
Prettier-eslint-cli: Allows you to format multiple files using prettier-eslint.
-
-
Configuration is prettier
- Create in the root directory of the project
.prettierrc.js
File and configureprettier
Code inspection rules:
// .prettierrc.js module.exports = { // Let Prettier use esLint's code format for validation eslintIntegration: true./ / the indentation tabWidth: 2.// Use TAB or space useTabs: false.// Contains a maximum of 80 characters printWidth: 200.// End-of-line semicolon semi: false./ / single quotation marks singleQuote: true.// JSX double quotes jsxSingleQuote: false.// Use trailing commas whenever possible (including function arguments) trailingComma: "none".// Prints Spaces between parentheses in the object text. bracketSpacing: true.// > The tag is placed at the end of the last line, not on its own on the next line jsxBracketSameLine: false.// Arrow parentheses arrowParens: "avoid".// Insert a special @format tag at the top of the file to specify that the file format needs to be formatted. insertPragma: false.// End of line newline format endOfLine: "auto".HTMLWhitespaceSensitivity: "ignore"};Copy the code
- Update it again
eslint
Configuration to handleprettier
andeslint
In the conflict.
// .eslintrc.js module.exports = { // Other configuration... extends: [ // Inherit vUE's standard features "plugin:vue/essential"."eslint:recommended"."prettier",].// Other configurations remain unchanged... }; Copy the code
- Create in the root directory of the project
After esLint and Prettier are installed and configured, husky + Lint-staged + Commitlint + preprogrammed hooks are added to commit operations to automatically check code and format code before committing
Husky + Lint-Staged + Commitlint installation and configuration
Husky is a tool that adds hooks to Git clients. Once installed, it automatically adds hooks to the.git/ directory in your repository. For example, a pre-commit hook will trigger when you perform a Git commit. You can implement things like Lint checking, unit testing, and code beautification in pre-commit. Of course, make sure that the command speed is not too slow in the pre-commit phase. It is not good to wait for a long time for each commit.
Lint-staged, a tool that simply filters out Git code staging files (files added by Git); This is useful because if we do a review of the entire project code, it can take a long time, and if we do an older project, we have to do a code specification review of the previous code and modify it, which can be troublesome, and can lead to major changes in the project. So this Lint-staged project is a great tool for team projects and open source projects, which act as a specification and discipline for the code that individuals must commit.
HooksPath allows you to specify the directory where git hooks are located instead of using the default. Git /hooks/, Husky can use husky install to specify the.husky/ directory for which the hooks are located, and then use the husky add command to add hooks to.husky/. This way we can add only the git hooks we need, and all the scripts are saved in one place (.husky/) so there are no synchronization problems.
Install and configure Husky
-
Install the husky
npm i husky --save-dev Copy the code
-
Add the prepare script in package.json
{..."scripts": { "dev": "vite"."build": "vite build"."serve": "vite preview"."prepare": "husky install".// Add the prepare script}... }Copy the code
-
Executing the prepare script
npm run prepare Copy the code
When the husky install command is executed, it creates the. Husky/directory and specifies that directory as the directory where git hooks are located.
-
To add Git hooks, run the command to create git hooks
npx husky add .husky/pre-commit "npm run lint" Copy the code
After running this command, we will see a new shell script named pre-commit in the. Husky/directory. This means that the pre-commit script will be executed before git commit. The pre-commit script content is as follows:
#! /bin/sh . "$(dirname "$0")/_/husky.sh" npm run lint Copy the code
The function of this script is to execute the command NPM run lint
-
Add the commit- MSG script and run the following command
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"' Copy the code
After running this command, we will see that a shell script named commit-msg has been added to the.husky/ directory. Commitlint can perform format specification verification for COMMIT MASSAGE, and the commit-msg script content is as follows:
\#! /bin/sh "$(dirname "$0")/_/husky.sh" npx --no-install commitlint --edit "The $1" Copy the code
Install the configurationlint-staged
-
Install the lint – staged
npm i lint-staged --save-dev Copy the code
-
The command to configure Lint in package.json file
{..."scripts": { "dev": "vite"."build": "vite build"."serve": "vite preview"."prepare": "husky install".// Add the prepare script "lint": "lint-staged --allow-empty"}... }Copy the code
-
Configure lint-staged commands
Starting with V3.1, lint-staged configuration can be done in different ways:
-
Configure in package.json file
{..."lint-staged": { "src/**/! (*.min).js": [ "prettier --write"."eslint --fix"]."src/**/*.{ts,vue}": [ "prettier --write"."eslint --fix"]."src/**/*.{ts,js,vue,html,css,scss,sass,stylus}": [ "prettier --write"]},... }Copy the code
“src/**/! (*.min).js” indicates that all.js files in the SRC directory except.min.js end need to be formatted
-
Use the.lintStageDRC file for configuration, supporting JSON or YML format syntax
-
Configure using a file in lint-lanterns.config. js format
"use strict"; module.exports = { "{src,server}/**/! (*.min).js": [ "eslint --fix"."prettier --write"]."{src,server}/**/*.{ts,vue}": [ "eslint --fix"."prettier --write"]."src/**/*.{html,css,scss,sass,stylus}": [ "prettier --write"]}Copy the code
-
Pass the configuration file for configuration using the –config or -c flag
-
Finally, configure commitLint to customize the COMMIT specification
Commitlint custom commit specifications
Commitlint what commitlint is: a tool to check if XXX meets a fixed format when we run git commmit -m ‘XXX’.
Why use CommitLint: The COMMITLint specification provides a clearer view of each code commit record and the ability to automatically generate changeLog files based on custom rules.
-
Commitlint installation
npm install --save-dev @commitlint/config-conventional @commitlint/cli Copy the code
-
@commitlint/cli is a command line tool provided by commitlint. After installation, cli scripts are stored in the./node_modules/. Bin/directory
-
Commitlint/config-Conventional are shared configurations in the community, which we can extend or customize without installing this package
-
-
Customize submission format
The basic code submission format is:
(scope?) :
Type: indicates the type of change we are committing this time. Is it new functionality? Or did you change the test code? Or is it a document update? Scope: An optional modification scope. Identifies which module in the code is primarily involved in this commit. Subject: Describe the main content of this submission in one sentence, and make it brief and comprehensive
-
Common type categories
type | describe |
---|---|
ci | Continuous integration modification |
docs | Document revision |
feat | New features, new functions |
fix | Modify the bug |
perf | Optimization related, such as improved performance, experience |
refactor | Code refactoring |
revert | Roll back to the previous version |
style | Code format modification, note not CSS modification |
test | Test case modification |
build | Compile-related changes, such as releases, changes to project builds, or dependencies |
chore | Other modifications, such as changing the build process, or adding dependent libraries, tools, and so on |
update | Regular updates |
Usage:
git commit -m 'Feat: Add XXX function'
git commit -m 'Fix (account): Fix XXX bug'
Copy the code
-
Create a file named commitlint.config.js in the project root directory as follows:
/* * @description: commit- MSG:
(scope?) : module.exports = { extends: ['@commitlint/config-conventional'].rules: { 'type-enum': [ 2.'always'['ci'.'docs'.'feat'.'fix'.'perf'.'refactor'.'build'.'chore'.'revert'.'style'.'test']],'type-empty': [2.'never'].//* -type: used to indicate the type of change we are committing this time. Or did you change the test code? Or is it a document update? * -build: compile-related modifications, such as releases, or changes to the project build or dependencies * -chore: Other modifications, such as changes to the build process, or additions to the dependent libraries, tools, etc. * -ci: Continuous integration modifications * -docs: document modifications * -feat: -refactor: refactoring: code refactoring: rolling back to a previous version * -style: Code format modification, not CSS modification * -test: test case modification * -scope: an optional modification range. Identifies which module in the code is primarily involved in this commit. * -subject: Describe the main content of the submission in one sentence, and make it brief */ cannot be empty / / 'type - case: [2,' always', 'the lower - case], / / < type > format lowercase 'type-case': [0].'scope-empty': [0]./ / 'scope - case: [2,' always', 'the lower - case], / / the < scope > format lowercase 'scope-case': [0].'subject-empty': [2.'never'].//cannot be empty (default) / / 'subject -- full stop: [2,' never ', '. '], / / < subject > in. For closing mark 'subject-full-stop': [0.'never'].// 'subject-case': [2, 'never', 'lower-case'], 'subject-case': [0.'never'].// case Optional value // 'lower-case' lowercase lowercase // 'upper-case' UPPERCASE // 'camel-case' camelCase // 'kebab-case' short line kebab-case // 'pascal-case' PascalCase // 'sentence-case' uppercase sentence case // 'snake-case' underline snake_case // 'start-case' uppercase all letters start-case 'header-max-length': [0.'always'.72].// The length of the header is 72 // 'body-leading-blank': [2, 'always'], // body newline // 'footer-leading-blank': [1, 'always'], // }};Copy the codeA rule consists of a name and configuration array, such as: ‘name: [0, ‘always’, 72] “, said one of the first level in the array, optional,1,2,0 0 to disable, 1 to warning, 2 for the error, the second indicates whether or not the application, the optional always | never, a third said the value of the rule.
-
If the format of the COMMIT message does not meet the preceding requirements, an error message is displayed and the check fails
✔ Preparing... ✔ Running tasks... ✔ Applying modifications... ✔ Cleaning up... ⧗ input: Modify bug * subject may not be empty [subject-empty] * found 1 problems, 0 warnings ⓘ Gethelp: https://github.com/conventional-changelog/commitlint/#what-is-commitlint husky - commit-msg hook exited with code 1 (error) Copy the code
At this point, the whole set of process tools are configured. Perform the following operations:
- Code changes (formatted only after file changes from specified directories configured in Lint-staged)
- perform
git add .
Add the changes to the staging area - perform
Git commit -m "feat:
The program automatically performs code inspection, code formatting, and then commit.
Of course, if you don’t want to commit your code for now, you can do this by executing git Add. NPM run Lint directly executes the NPM run lint command to check and format the code before continuing development.
The above rules are uniformly configured in the project during team development. Team members only need to pull the code and execute NPM install to use it.
We can also use VSCode with plug-ins for code checking, prompting, and formatting. The eslint configuration in VSCode is shared below.
VSCode configures eslint and formatting
Eslint, prettier, and vetur plugins can be configured in vscode to check and prompt code when editing according to eslint error levels, and to automatically fix and format files when saving, making development easier.
Some projects may not have a standardized process (husky+lint-staged+commitlint+eslint) configured, and some projects may not be scaffolded, so using vscode with plug-ins is a great idea.
Next, configure vscode:
Install the VsCode extension
-
Install the Eslint, Prettier, and Vetur plugins first.
-
Then open the setting.json file and add the following configuration so that it will be automatically formatted when saved in VScode (CTRL +s) :
{ "eslint.alwaysShowStatus": true.// Run the linter on save (onSave) or on type (onType) "eslint.run": "onType".// # automatic formatting every time you save "editor.formatOnSave": false.// # fix the code in ESLint format every time you save it // "eslint.autoFixOnSave": false, // here is the new version of vscode configuration "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "eslint.validate": [ "javascript"."javascriptreact", { "language": "html"."autoFix": true }, { "language": "vue"."autoFix": true},]."vetur.format.options.tabSize": 2.// HTML formatting dependency defaults to None using the built-in prettyHTML "vetur.format.defaultFormatter.html": "js-beautify-html".// Let the js in vue be formatted according to the ts format provided by the editor "vetur.format.defaultFormatter.js": "vscode-typescript"."vetur.format.defaultFormatterOptions": { "js-beautify-html": { // #vue component HTML code formatting style // "preserve_newlines": true, // allow blank lines // "wrap_attributes": "force-aligned", // "wrap_attributes": "force-expand-multiline", // "wrap_attributes": "aligned-multiple", "wrap_attributes": "preserve-aligned"."wrap_line_length": 0."indent_size": 2.// "end_with_newline": true}},// Let Prettier use esLint's code format for validation "prettier.eslintIntegration": true."prettier.semi": true.// Whether to add a semicolon "prettier.tabWidth": 2.// The number of Spaces per TAB (set according to the project's code specification) "prettier.useTabs": false.// Indent instead of TAB, use Spaces "prettier.singleQuote": true.// Wrap a string around a single quote "prettier.printWidth": 600.// The maximum width of a single line of code "prettier.endOfLine": "auto".// It ends with \n\r \n\r auto "prettier.jsxBracketSameLine": false.// Whether to put '>' on a single line in JSX "prettier.jsxSingleQuote": false.// Use single quotes instead of double quotes in JSX Vetur. Validation. / / "template" : true, / / used to examine the code < template > section Init () {} () {} () {} "javascript.format.insertSpaceBeforeFunctionParenthesis": false.// Whether to place a space between the parentheses and es5-style function names Function init() {} function init() {} function init() {} "javascript.format.insertSpaceAfterFunctionKeywordForAnonymousFunctions": false."[vue]": { // Vue files are formatted using vetur "editor.defaultFormatter": "octref.vetur" }, "[javascript]": { // "editor.defaultFormatter": "vscode.typescript-language-features" "editor.defaultFormatter": "esbenp.prettier-vscode" // Can automatically save files of specified type separately and coexist with editor.codeActionsOnSave // "editor.formatOnSave": true }, "[html]": { "editor.defaultFormatter": "esbenp.prettier-vscode" // "editor.defaultFormatter": "HookyQR.beautify" // Can automatically save files of specified type separately and coexist with editor.codeActionsOnSave // "editor.formatOnSave": true }, "[scss]": { "editor.defaultFormatter": "michelemelluso.code-beautifier" // Can automatically save files of specified type separately and coexist with editor.codeActionsOnSave // "editor.formatOnSave": true}},Copy the code
Note: if both global and project-specific eslint dependencies are installed, VScode will not detect them, so you have to choose between global and project-specific dependencies.
The configuration in VsCode can be customized and adjusted according to the project development specifications or your own custom