Writing in the front
On a team development project, if there is no code style requirement, there will of course be as many different code styles as there are team members. Therefore, we need a tool that can unify the team’s code style, as a mandatory specification, to unify the code style of the entire project.
Luckily, we have EsLint and Prettier.
eslint VS prettier
Most projects should already adopt ESLint for quality checking of code, and perhaps a few will adopt some degree of uniformity. So why prettier? Let’s take a quick look at them.
Various linters
Overall, Linters have two abilities:
- Check code quality, such as whether there are defined but unused variables, or whether there are side effects from using functionally programmed functions.
- Check code style, such as maximum line length, or whether trailing commas are used.
Rules with wrench ICONS in ESLint documentation are rules that ESLint can fix automatically. Eslint, on the other hand, can only issue errors or warnings for rules without the icon, which can then be manually fixed by the developer.
prettier
Pretter does not have the ability to check the quality of code. Instead, it will only unify code styles according to specified specifications to avoid multiple code styles in a project.
Project configuration
The VUE project is used here as an example
First, configure ESLint
If your project is generated using the Vue CLI and you choose to use ESLint,.eslintrc.js will be generated in the project root directory by default. If not, you can also create this file in the project root along with the.eslintignore file
Here I use eslint-plugin-vue and choose the vue/ welson-recommended rule.
npm install --save-dev eslint eslint-plugin-vue@next
Copy the code
// .eslintrc.js
extends: {
'plugin:vue/strongly-recommended'
}
Copy the code
// .eslintignore
/build/
/config/
/dist/
/*.js
/test/unit/coverage/
Copy the code
If you want ESLint to fix code automatically at recompile time, you need to add ESLint to the WebPack configuration, set fix: true, and enable ESLint in DevServer.
// config/index.js
module.exports = {
dev: {
useEslint: true,}}Copy the code
// webpack.base.conf.js
const createLintingRule = (a)= > ({
test: /\.(js|vue)$/.loader: 'eslint-loader'.enforce: 'pre'.include: [resolve('src'), resolve('test')].options: {
formatter: require('eslint-friendly-formatter'),
emitWarning: !config.dev.showEslintErrorsInOverlay,
fix: true,}})Copy the code
2. Configure prettier
Prettier was introduced because esLint was not the most uniform code style possible.
npm install --save-dev prettier
Copy the code
Configure prettier as required
//prettier.config.js
module.exports = {
"printWidth": 80.// Length per line (default 80)
"tabWidth": 2.// How many Spaces per TAB (default: 2)
"useTabs": false.// Whether to indent with TAB (default false)
"singleQuote": true.// Use single quotes (default false)
"semi": true.// Declaration ends with a semicolon (default true)
"trailingComma": "all".// Use trailing commas for multiple lines (default none)
"bracketSpacing": true.// Use Spaces between braces for object literals (default true)
"jsxBracketSameLine": false.// In multi-line JSX, the > is placed at the end of the last line instead of starting on another line (default false)
"arrowParens": "avoid" // Avoid parentheses for arrow functions with only one argument (default: avoid)
};
Copy the code
Json to format by calling prettier
// package.json
"scripts": {
"format": "prettier --write \"src/**/*.js\" \"src/**/*.vue\"",}Copy the code
At this point, you can format your code by typing NPM run format on the command line.
Configure HusKY and Lint-staged
Formatting code directly using Prettier still has some drawbacks, such as:
- Formatting everything at once. Adding Prettier in the middle of a project would format code that had already been written, possibly causing conflicts or unpredictable problems that could reduce project stability.
- NPM run format has to be typed every time for code formatting, resulting in additional operations and poor development experience.
Therefore, we can modify the timing of the code formatting to only format the code submitted this time and before the code is submitted to ensure that the code stored in the repository is formatted and good.
Husky is a third-party library that allows you to use hooks defined in the package.json file and set to be used by the commands that the hooks execute.
Lint-staged (antinoline) is a third-party library that can use Linter against Git submitted code, relying on Husky to use Git hooks. Here we can use it to format code not just by calling linters, but also by calling prettier.
npm install --save-dev lint-staged husky
Copy the code
// package.json
"scripts": {
"precommit": "lint-staged" // PreCOMMIT hooks perform Lint-staged
},
"lint-staged": {
"src/**/*.{js,json,css,vue}": [
"prettier --write".Prettier before esLint to ensure code quality
"eslint --fix"."git add"]},Copy the code
4. Use esLint and prettier together
Because Prettier needs to be used alongside EsLint and some of Prettier’s rules might conflict with esLint’s rules, esLint needs to disable code formatting rules that would conflict with Prettier. Eslint-plugin-prettier and eslint-config-prettier are used here.
Eslint-plugin-prettier You can configure the prettier rule as the rule of ESLint to prompt those who do not conform to the rule. (Same as eslint-plugin-vue)
Eslint-config-prettier Shuts off code formatting rules that esLint might conflict with Prettier. Officials say eslint-plugin-prettier needs to be used alongside eslint-config-prettier for best effect.
npm install --save-dev eslint-plugin-prettier eslint-config-prettier
Copy the code
// .eslintrc.js
module.exports = {
extends: [
'plugin:vue/strongly-recommended'.'plugin:prettier/recommended'
]
rules: {
"prettier/prettier": "error"}}Copy the code
Prettier and ESLint formatting and quality checking the code before committing git commit
Overall configuration file
npm install -D prettier husky lint-staged eslint-config-prettier eslint-plugin-prettier
Copy the code
// package.json
{
"scripts": {
"format": "prettier --write \"src/**/*.js\" \"src/**/*.vue\""."precommit": "lint-staged"
},
"lint-staged": {
"src/**/*.{js,json,css,vue}": [
"prettier --write"."eslint --fix"."git add"]},"devDependencies": {
"eslint": "^ 4.15.0"."eslint-config-prettier": "^ 2.9.0"."eslint-plugin-prettier": "^ 2.6.2." "."eslint-plugin-vue": "^ 4.0.0"."husky": "^ 0.14.3"."lint-staged": "^ 7.2.0"."prettier": "^ 1.14.2",}}Copy the code
// eslintrc.js
// https://eslint.org/docs/user-guide/configuring
module.exports = {
extends: [
'plugin:vue/strongly-recommended'.'plugin:prettier/recommended'].// add your custom rules here
rules: {
/ /... other codes
"prettier/prettier": "error"}}Copy the code
//prettier.config.js
module.exports = {
"printWidth": 80.// Length per line (default 80)
"tabWidth": 2.// How many Spaces per TAB (default: 2)
"useTabs": false.// Whether to indent with TAB (default false)
"singleQuote": true.// Use single quotes (default false)
"semi": true.// Declaration ends with a semicolon (default true)
"trailingComma": "all".// Use trailing commas for multiple lines (default none)
"bracketSpacing": true.// Use Spaces between braces for object literals (default true)
"jsxBracketSameLine": false.// In multi-line JSX, the > is placed at the end of the last line instead of starting on another line (default false)
"arrowParens": "avoid" // Avoid parentheses for arrow functions with only one argument (default: avoid)
};
Copy the code
Write in the last
An IDE that incorporates esLint or Prettier by default checks code against configuration files in the project root directory.
If vscode is used, the default code for Vetur stylizes prettier, which automatically retrieves the prettier configuration file in the project root directory for formatting. The ESLint retrieval tool recommends using the ESLint plugin, which automatically retrieves esLint configuration files for code inspection after installation.
The above is my practice of standardizing code style, referring to the practices of various countries, and formulating norms in line with the actual project.
If there is a better and more convenient way to unify the code style, please do not hesitate to let me know, thank you!