📅  最后修改于: 2023-12-03 14:41:01.290000             🧑  作者: Mango
When it comes to writing code, maintaining a consistent standard is one of the most challenging aspects. That's where ESlint comes in. ESlint is a tool for creating clear and understandable code that is consistent throughout the team.
In this guide, we'll explore how to set up ESlint to perform operations automatically when you save your code. By doing this, you can ensure that your code adheres to the standards you have set, making it easier to read and understand.
Before we start, we need to install ESlint. You can do this using npm, the Node.js package manager. Type the following command in your terminal:
npm install eslint --save-dev
After installing ESlint, create a new file in your project root called .eslintrc.js
. This file will contain the configuration for ESlint.
Now that we have installed ESlint and created a configuration file, we can start setting up the automated operations. Here's an example .eslintrc.js
file with some basic configuration:
module.exports = {
env: {
browser: true,
es6: true
},
extends: 'eslint:recommended',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module'
},
rules: {
indent: ['error', 2],
'linebreak-style': ['error', 'unix'],
quotes: ['error', 'single'],
semi: ['error', 'always']
},
overrides: [
{
files: ['*.test.js'],
env: {
jest: true
}
}
]
}
This file sets up some basic rules for ESlint to follow. For example, indent
enforces that code is indented with two spaces, linebreak-style
ensures that line breaks are consistent, quotes
enforces the use of single quotes instead of double quotes, and semi
enforces the presence of semicolons at the end of lines.
Now that we have configuration set up, we can set up on-save operations. For this, we'll use a tool called Husky.
First, install Husky using npm:
npm install husky --save-dev
Next, update your package.json
file to include a prepare
command that will run eslint
:
"scripts": {
"prepare": "eslint --fix src"
},
This tells Husky to run the eslint
command with the --fix
option every time you save a file.
Finally, add the following configuration to your .huskyrc.js
file:
module.exports = {
hooks: {
'pre-commit': 'npm run prepare'
}
}
Now, every time you commit code, Husky will run the prepare
command, which will automatically process your code with ESlint.
By setting up ESlint and Husky, you can ensure that your code adheres to the standards you have set. This makes it easier to read and understand, especially when working in a team. Remember, consistency is key in writing clean and clear code!