It is important for a project to maintain a consistent code style to improve the quality and readability of the code. In this article, ESLint and Prettier will be introduced to some of their core concepts and basic uses. ESLint + Prettier improves code Quality (2) : How to integrate Vue and React projects
The difference between ESLint and Prettier may not be clear to some. Prettier does not format code as well as Prettier, which formats code regardless of quality. For example, an error occurs when an undeclared variable is used.
ESLint
The basic use
1. Create a configuration file
The configuration can be done in package.json’s eslintConfig, or you can manually create a.eslintrc.(js,yml,json) file, or you can use the following command (recommended) :
npx eslint --init
Copy the code
There are a series of questions and answers on the cli, and you can select the appropriate configuration as required.
2. Check
You can then use the following command to verify any file or directory:
npx eslint fileName | directory
Copy the code
Configuration file details
rules
A key item in the configuration file is rules, which you can configure for your team:
{
"rules": {
"semi": ["error", "always"],
"quotes": ["error", "double"]
}
}
Copy the code
The first parameter controls the error level of the rule, including the following three levels:
- “Off” or 0: disables the rule
- “Warn” or 1: will not cause code exit
- “Error” or 2: Code compiles and exits
extends
Some third-party shared configuration can be introduced, such as eslint-config-Airbnb. The following configuration uses the common checkbox Rules.
{
"extends": ["eslint:recommended"] // Format: "package name: rule"
}
Copy the code
The eslint-config- prefix must be omitted.
If rules and extends are empty, ESLint won’t actually lint code.
plugins
Extends ESLint. For example, add some rules, or export Shareable Configurations. The eslint-plugin- prefix needs to be omitted:
{
"plugins": [
"react" / / eslint - plugin - namely the react]."extends": [
"eslint:recommended"."plugin:react/recommended" // Format: plugin package name/Configuration name]."rules": {
"react/no-set-state": "off" // Plugin package name /rule name}}Copy the code
overrides
Separate rules can be used for matched files in certain directories:
"overrides": [
{
"files": ["bin/*.js", "lib/*.js"],
"excludedFiles": "*.test.js",
"rules": {
"quotes": ["error", "single"]
}
}
]
Copy the code
root
Eslint will start with the file currently being lint and go up until it finds either a configuration file marked root:true or the root directory of the entire file system (config files found along the way are merged). You are advised to set the config file in the root directory of the project to root:true.
env
Provides global variables for the corresponding environment. Such as:
{
"env": {
"browser": true,
"node": true
}
}
Copy the code
parserOptions
Configure the supported JS. The default is ES5.
{ "parserOptions": { "ecmaVersion": "latest", "sourceType": "module", "ecmaFeatures": { "jsx": Eslint-plugin-react}}, "rules": {"semi": "error"}}Copy the code
With VScode integration
Search ESLint in the plugin market, install the plugin, and configure it in IDE Settings. json:
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
Copy the code
Integrate Husky and Lint-staged
Lint and fixes before committing code. The following two tools need to be integrated:
- husky: At the corresponding stage of Git (
Pre-commit, commit-msg, and pre-push
) command to trigger the configuration. - Lint-staged: Run linters on git temporary files, ignoring history files.
Configuration husky
1. Install dependencies
npx husky-init && npm install
Copy the code
This command installs husky dependencies; Create the. Husky directory, which contains the pre-commit hook file, in which you can configure the commands to trigger the hook. Package. json added a script:
{
"scripts": {
"prepare": "husky install"}}Copy the code
2. The configuration.husky/pre-commit
Husky /pre-commithook file:
#! /bin/sh . "$(dirname "$0")/_/husky.sh" # eslint --fix ./src --ext .vue,.js,.tsCopy the code
Configuration lint – staged
1. Install dependencies
npm i lint-staged -D
Copy the code
2. Add to package.json:
{
// ...
"lint-staged": {
"*.{vue,js,ts}": "eslint --fix" // Configure it as required}},Copy the code
Eslint –fix only for.vue,.js,.ts files in git staging.
3. Modify.husky/pre-commit
Hook:
#! /bin/sh. "$(dirname "$0")/_/husky.sh" # eslint --fix./ SRC -- ext.vue,.js,.ts # This will have passage passage for historical files Lint NPX lint-passage # Lint only for files added this timeCopy the code
This way, files in Git Staged will be linted each time a Git COMMIT is performed.
Prettier
The difference with ESLint is that it focuses on the format of the code, regardless of whether there are any syntax errors, and does not care about the quality of the code. Supports multiple languages such as JS, TS, JSON, CSS, Vue, and React.
Use Prettier for formatting and linters for catching bugs.
The basic use
1. Install
npm install --save-dev --save-exact prettier
Copy the code
Save-exact indicates that the fixed version is installed. There is no ^ or ~ in front of it. It is recommended to lock in a clear version number, otherwise even minor updates may result in rule changes.
2. Create a configuration file in the. Prettiertc,. Prettierrc.[js/json] format.
.prettierrc.js
: Configure specific format rules:
module.exports = {
semi: false.trailingComma: 'all'.singleQuote: true.printWidth: 120.tabWidth: 2};Copy the code
.prettierignore
Directories or files that do not need format can be configured in.
Use 3.
npx prettier --write .
Copy the code
. Indicates all files. You can specify files or directories.
Used with ESLint
Because Prettier’s rules for format conflict with ESLint, install the following package to disable format in ESLint and use the rules for Prettier:
- Eslint-config-prettier: Disables the stylistic rule that conflicts with Prettier in ESLint.
Prettier can also be used as a rule for ESLint by installing the following plug-in:
- Eslint-plugin-prettier: Let Prrettier run as a Linter rule. This way the IDE can directly use the integration solution with Linter.
Configuration. Eslintrc. Js file, will the plugin: prettier/it as the last extention:
{
"extends": ["plugin:prettier/recommended"]
}
Copy the code
It unfolds as follows:
{"extends": ["prettier"], // eslint-config-prettier "plugins": ["prettier"], // Eslint-plugin-prettier "rules": {"prettier/prettier": "error", // Open the rule provided by the plugin and run it as an ESLint rule "arrow-body-style": "off", "prefer-arrow-callback": "off" } }Copy the code
With VScode integration
Where Prettier is used, settings.json specifies formatter:
{
"editor.defaultFormatter": "esbenp.prettier-vscode"."[javascript]": { // Use prettier for files in a certain language
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"editor.formatOnSave": true
}
Copy the code
Example: If ESlint is used with ESlint and eslint-plugin-prettier is installed, it runs as a rule for ESlint, no need to configure VSCode for Prettier, just integrate ESlint:
{
"editor.defaultFormatter": "esbenp.prettier-vscode"."editor.codeActionsOnSave": {
"source.fixAll.eslint": true}}Copy the code
If you are not clear or wrong, you are welcome to leave a message for discussion. ESLint + Prettier improves code Quality ESLint + Prettier improves code quality when configuring Vue and React
reference
- ESLint base: Configuring ESLint
- Prettier Basis: Prettier
- ESLint configuration in VSCode: the ESLint plugin