ESLint+Prettier code specification practice
The premise
This article does not explain how ESLint and Prettier are configured and run in isolation.
The problem
Want to enforce certain code specifications in the team, and to detect and alert non-conforming code.
plan
The code specification validates using ESLint, but at first ESLint only checks to tell you what’s wrong, which is often a bunch of warnings that can be painful to change. $ESLint filename –fix ESLint filename –fix $ESLint filename –fix Prettier Prettier is a code formatter that formats code into a more readable format, typically when a line of code is too long.
Lint is different from Prettier
So what’s the difference between ESLint and Prettier? The main functionality of ESLint (and some other Lint tools) includes verification of code format, and verification of code quality. Prettier, on the other hand, just checks code format (and formats code), not code quality. Code format problems usually refer to: single line code length, TAB length, Spaces, comma expressions, etc. Code quality issues are: unused variables, equal signs, global variable declarations, etc.
Lint and Prettier are used together
Why do they work together? For one thing, before the –fix parameter was introduced, ESLint did not automate formatting code, so the only way to do bulk formatting for formatting problems was using a tool like Prettier. Second, ESLint’s rule does not necessarily include Prettier’s rule; it is not simply a question of who replaces whom. But after ESLint introduced the –fix command-line argument, you don’t have to use Prettier if you think the formatting code ESLint provides is enough.
ESLint and Prettier have a few problems when they work together. ESLint and Prettier format different code for some of the rules where they intersect. The problem is that when you format code using Prettier and then use ESLint to detect it, there will be some warning caused by formatting. There are two solutions at this point:
- After Prettier is run, format esLint –fix so that conflicting parts are written out of ESLint’s format and the rest of the warning is code quality.
- Disable the rule that conflicts with Prettier when configuring ESLint’s verification rule, and then use the Prettier rule as the verification rule. Formatting Prettier without warning when ESLint checks where Prettier is used
Why can’t you use ESLint before Prettier Prettier for scenario 1, if you use Prettier later, formatted submitted code will not pass Lint the next time someone else checks out code. For scenario 2, yes, but I’ve seen community scenarios in practice where I’ve mentioned formatting problems when esLint –fix and prettier are mixed. So it’s safe to format with perttier first and verify with eslint instead of using eslint –fix to format.
Used to summarize
1. Front-end projects must standardize the code, whether it is JS or TS projects. 2. Prettier is good at checking code format, esLint is good at checking code quality. While ESLint can format verification, it is not as powerful as Prettier. The order in which esLint and prettier are used was explained earlier. 3. Vscode and its plug-in (PritTier) can easily achieve uniform coding format style, gradually strengthen the code unity problem in team collaboration, and then combine git Hook to achieve ESLint verification, then the team code style and quality can remain consistent.
The project practice
At present, there are three popular schemes, namely Airbnb, Standard and Google. The comparison of severity is Airbnb > Google > Standard, so Airbnb is widely used.
For ESLint, practice for prettier rule conflict
Plan a
-
Install Prettier-esLint (Tip: All scenarios where you already have ESLint and the package prettier installed)
$ npm install --save-dev prettier-eslint prettier-eslint-cli Copy the code
-
run
$ npm prettier-eslint "src/**/*.js" Copy the code
Prettier-eslint the prettier and eslint –fix commands are executed at once. Code ➡️ prettier ➡️ ESLint –fix ➡️ Formatted Code. Prettier-eslint for the various arguments for prettier-esLint, see github.com/prettier/pr… .
Scheme 2
The idea behind scenario 2 is to override the prettier rule by installing a plugin on the esLint rule configuration file and adding it to the end of the rule where Prettier is used.
-
Install the plugin:
$ npm install --save-dev eslint-config-prettier Copy the code
-
The extends field in the.eslintrc.* file adds:
{" extends ": [... and" already configured rules "+" prettier, "+" prettier / @ typescript - eslint "]}Copy the code
I use TypeScript, so the plugin name is prettier/@typescript-eslint.
If you want to disable more rules can be as follows:
{ "extends": [..., "already configured rule ", "prettier", "prettier/@typescript-eslint", "prettier/ Babel ", "prettier/flowtype", "prettier/react", "prettier/standard", "prettier/unicorn", "prettier/vue" ] }Copy the code
The name of the rule should tell you which rules are disable.
-
Prettier the esLint command does prettier verification, but you still need to run prettier and esLint separately. The community has a solution that combines the two steps by actually using Prettier instead of ESLint’s formatting function when using ESLint –fix. Installation:
$ npm install --save-dev eslint-plugin-prettier Copy the code
Modify. Eslintrc. *
{" extends ": [...," already configured rules ", "plugin: prettier/it"]}Copy the code
When you run esLint –fix, you use Prettier to format the file. Eslint-plugin-prettier For details, see github.com/prettier/es…
Integrated with VSCode
All of this is done after you’ve written the code, using the command line tool. If you’re new to the specification and not familiar with it, the problem is that you’ll get a lot of warnings after writing code and running command line tools. It’s really discouraging to change at this point. If you can have the editor prompt at the time of writing the code, it can be corrected in time. Of course, there are a lot of solutions available in our community, with plugins for Atom, Sublime, VSCode and other major editors. I’ll take VSCode as an example:
- Download ESLint Extension
Vscode plug-in
For ease of development, we often integrate helper plug-ins into VSCode. Example prettier, ESLint –fix, etc., where code prettier when saved or changed Modify the ESLint configuration in settings.json:
{'eslint.enable': true, // Whether to enable VScode eslint 'eslint.autoFixOnSave': true, // Whether to automatically fix eslint 'eslint.options' when saving: {// Specify the extensions to vsCode's esLint files: ['.js', '.ts', '.tsx'],}, 'eslint.validate': [// Determine validation criteria 'javascript', 'javascriptreact', {language: 'HTML ', autoFix: true,}, {language: 'typescript', autoFix: true, }, { language: 'typescriptreact', autoFix: true, }, ], };Copy the code
- Configuration. The eslintrc. *
module.exports = { parser: '@typescript-eslint/parser', extends: [ 'plugin:@typescript-eslint/recommended', 'prettier/@typescript-eslint', 'plugin:prettier/recommended' ], ParserOptions: {ecmaVersion: 2018, sourceType: 'module'}, // Other configurations};Copy the code
-
Because I’m using TypeScript, the.eslintrc.* config item has a slightly different value than javascript, but the principle is the same. If you’re not using TypeScript, the above step ends. However, VSCode’s ESLint plugin doesn’t naturally support ts files, so we’ll have to create our own Settings file. Create a.vscode/settings.json file in the root directory of the project.
{ "eslint.validate": [ "javascript", "javascriptreact", { "language": "typescript", "autoFix": true }, { "language": "typescriptreact", "autoFix": true } ] } Copy the code
You can see the editor prompt the code in real time.
Enforce checksum formatting
This has already been described, but these steps rely on manual compulsion. Husky Lint-staged force-staging can be used to enforce formatting and validation prior to Git commit.
-
The installation
$npm install --save-dev husky lint-staged Copy the code
-
Modify the package. The json:
{ "name": "project-name", ... , + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [ + "prettier --write", + "eslint", + "git add" + ] + }, }Copy the code
-
Prettier when you run git commit, prettier is automatically run –write formatting code, esLint is run to verify compliance. The code will not be committed until both steps have passed. If any of these steps fail, the commit is stopped.
If you use scenario 1, Lint-staged configured commands:
{ "name": "project-name", ... , + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [ + "prettier-eslint", + "git add" + ] + }, }Copy the code
If you use eslint-plugin-prettier from Scenario 2, lint-staged configuration commands:
{ "name": "project-name", ... , + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [ + "eslint --fix", + "git add" + ] + }, }Copy the code