The Demo address
introduce
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.
Eslint is different from prettier
The main functionality of ESLint (and some other Lint tools) includes verification of code format, and verification of code quality. Prettier simply 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.
Eslint 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, ESLint and prettier configuration and dependencies must follow dependencies, such as when environment differences cause unnecessary Git commit. For example, 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 be 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.
Package. json Content Overview:
{
"scripts": {
"prettier": "prettier --write --single-quote \"src/**/*.tsx\""."lint": "eslint --fix --ext .tsx ./src"."format": "yarn prettier && yarn lint "
}
"lint-staged": {
"src/**/*.tsx": [
"yarn format"."git add"]},"husky": {
"hooks": {
"pre-commit": "lint-staged"}},"devDependencies": {
"@typescript-eslint/eslint-plugin": "^ 2.13.0"."@typescript-eslint/parser": "^ 2.13.0"."babel-eslint": "^ 10.0.1." "."eslint": "^ 6.8.0"."eslint-config-prettier": "^ 6.9.0"."eslint-import-resolver-babel-module": "^ 5.1.0"."eslint-plugin-import": "^ 2.19.1." "."eslint-plugin-prettier": "^ 3.1.2." "."eslint-plugin-react": "^ 7.17.0"."lint-staged": "^ 8.1.7." "."prettier": "^ 1.19.1"."react-native-typescript-transformer": "^ 1.2.12"."typescript": "^ 3.7.4." "}},Copy the code
Yarn add -d prettier esLint install base dependency yarn add -d prettier ESLint install base dependency yarn add -d prettier esLint install base dependency yarn add -d prettier esLint install base dependency yarn add -d prettier esLint install base dependency yarn add -d prettier esLint install base dependency yarn add -d prettier esLint
.eslintrc.js
module.exports = {
env: {
browser: true.es6: true.node: true,},extends: [
'airbnb-base',].globals: {
Atomics: 'readonly'.SharedArrayBuffer: 'readonly',},parser: '@typescript-eslint/parser'.parserOptions: {
ecmaVersion: 2018.sourceType: 'module',},plugins: [
'@typescript-eslint',].rules: {}};Copy the code
Env is used to specify environments. Each environment has its own predefined global variables, and multiple environments can be specified at the same time without contradiction. If the console attribute exists only in browser environments, if browser support is not set, console is undefined.
env: {
browser: true.es6: true.node: true.commonjs: true.mocha: true,},Copy the code
The extends property value can be a string or an array of strings in which each configuration item inherits its previous configuration and can modify, override, and extend the inherited rules. Our extends extends, for example, inherits Airbnb configuration rules.
extends: [
'airbnb-base'.// 'eslint:recommended',
// 'plugin:react/recommended',
// 'plugin:@typescript-eslint/eslint-recommended',
// 'plugin:@typescript-eslint/recommended',
// 'prettier/@typescript-eslint',
// 'plugin:prettier/recommended',
]
Copy the code
Additional global variables that the globals script accesses during execution. (Doesn’t seem to help)
Parser specifies a different parser. ESLint uses Espree as its default parser. TypeScript projects use the typescript-ESLint parser that the TypeScript team co-publishes with ESLint. It is very well compatible with TypeScript and ESLint parsing features. There are parsers such as Esprima and babel-ESLint.
yarn add -D @typescript-eslint/parser @typescript-eslint/eslint-plugin
Copy the code
ParserOptions specifies the environment configuration parameters that the parser wants to use.
parserOptions: {
ecmaVersion: 2019.// The default is 5, in our case we use the latest 2019.
sourceType: 'module'.// Defaults to 'script', but generally uses the ECMAScript module form 'module '
ecmafeatures: {
globalReturn: false.// Allow the use of return statements in the global scope
impliedStrict: false.// Enable global strict mode (strict mode)
jsx: false./ / enable JSX
experimentalObjectRestSpread: false / / to enable support for experimental objectRest/spreadProperties}}Copy the code
Add third-party plug-ins to plugins. Remember to install devDependencies in advance. Extend provides a set of presets for existing ESLint rules, while Plugin provides custom rules in addition to presets. If you can’t find one in ESLint’s rules, you can borrow a plugin to implement it.
plugins: ['prettier'.'@typescript-eslint'].Copy the code
Rules Additional ESLint specific rules, a complete list of rules.
prettier.config.js
Prettier refers to north when getting started.
As mentioned before, prettier just checks code and formats code, so rules are much simpler than ESLint –fix — ext.tsx./ SRC so preittier can be replaced by esLint –fix — ext.tsx. Prettier-code Formatter = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier = preitTier I usually configure prettier.config.js, not vscode-Prettier, so that the project is independent.
In actual combat
Because it is a React project, you need to add React related ESLint extensions and plug-ins.
yarn add -D eslint prettier
yarn add -D @typescript-eslint/parser @typescript-eslint/eslint-plugin
yarn add -D eslint-plugin-react
yarn add -D eslint-config-prettier eslint-plugin-prettier
Copy the code
Dependency description:
- @typescript-eslint/parser: Converts typescript to ESTree for ESLint to recognize.
- @typescript-eslint/eslint-plugin: List of rules that can be turned on or off.
- Eslint-plugin-react: Detects and regulates react code.
- 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.
- Eslint-plugin-prettier: The use of prettier as the ESLint specification.
Prettier. Config. Js is as follows:
module.exports = {
printWidth: 120.// Maximum length per line
tabWidth: 2.// A TAB represents several Spaces. The default is 80
useTabs: false.// Whether to use TAB for indentation. The default value is false, indicating that Spaces are used for indentation
semi: true.// Declaration followed by a semicolon
singleQuote: true.// Use single quotes
jsxSingleQuote: true.// Use single quotes
jsxBracketSameLine: true.// Enable JSX syntax, > at the end
trailingComma: 'all'};Copy the code
. Eslintrc. Js is as follows:
module.exports = {
env: {
// Specify the environment in which the code is run
browser: true.node: true,},settings: {
// Automatically discover the React version to regulate the React code
react: {
pragma: 'React'.version: 'detect',}},parser: '@typescript-eslint/parser'.parserOptions: {
// Specifies that ESLint can parse JSX syntax
ecmaVersion: 2019.sourceType: 'module'.ecmaFeatures: {
jsx: true,}},extends: [
// Use the recommended React code to test the specification
'plugin:react/recommended'.'plugin:@typescript-eslint/recommended'.'prettier/@typescript-eslint'.'plugin:prettier/recommended',].plugins: ['@typescript-eslint'].rules: {}};Copy the code
In the new extends configuration:
- Prettier /@typescript-eslint: Invalidation of the style specification in @typescript-esLint to conform to the style specification in prettier
- Plugin: prettier/it: use the prettier in style specification, and if make ESLint will detect prettier the format of the questions, the same will be thrown in the form of the error format problem
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 fix eslint automatically when saving
'eslint.options': {
// specifies the suffix for files handled by vscode's eslint
extensions: ['.js'.'.ts'.'.tsx'],},'eslint.validate': [
// Determine the verification criteria
'javascript'.'javascriptreact',
{
language: 'html'.autoFix: true}, {language: 'typescript'.autoFix: true}, {language: 'typescriptreact'.autoFix: true,}]};Copy the code
Reference:
- ESLint+Prettier code specification practice
- Use ESLint+Prettier to unify front-end code styles
- How to gracefully use ESLint and Prettier in Typescript projects