Preface
recently started a new project, want to do a good job of code specifications and constraints, in fact, there are a lot of scaffolding, project templates can be used directly, but do-it-yourself, can be completely self-matching.
install eslint
install and execute yarn add-- dev eslint
add .eslintrc.js to the project directory
module.exports = {
root: true, // specify root as true,eslint to check only the current project directory
env: {
// provide default global variables to prevent eslint from checking for errors, such as window
browser: true,
node: true,
es6: true,
},
extends: [
// inherit the inspection rules recommended by eslint
'eslint:recommended',
],
parserOptions: {
ecmaVersion: 'latest', // specify the ECMAScript syntax as up-to-date
sourceType: 'module', // specify the code as ECMAScript module
ecmaFeatures: {
jsx: true, // enable jsx
},
},
};
add .eslintignore
to the project directory, ignoring some directories and files that do not require eslint detection
.eslintrc.js
node_modules
dist
.DS_Store
*.local
install typescript-eslint
since the project uses Typescript
, you need to change the eslint interpreter. Refer to typescript-eslint .
install and execute yarn add-- dev @ typescript-eslint/parser @ typescript-eslint/eslint-plugin
change .eslintrc.js
module.exports = {
root: true, // specify root as true,eslint to check only the current project directory
env: {
// provide default global variables to prevent eslint from checking for errors, such as window
browser: true,
node: true,
es6: true,
},
extends: [
// share the recommended configuration style
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
parserOptions: {
ecmaVersion: 'latest', // specify the ECMAScript syntax as up-to-date
sourceType: 'module', // specify the code as ECMAScript module
ecmaFeatures: {
jsx: true, // enable jsx
},
},
};
install eslint-config-airbnb and eslint-config-airbnb-typescript
above we use the code style recommended by eslint
and typescript
.
extends: [ // share the recommended configuration style
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
but accustomed to airbnb code style, and it's quite popular.
We need to know before installation.
-
eslint-config-airbnb
is aAirbnb JavaScript
style eslint shared configuration library. Detection rules includeES6+
andReact
, which depend oneslint-plugin-import
,eslint-plugin-react
,eslint-plugin-react-hooks
, andeslint-plugin-jsx-a11y
packages. -
eslint-config-airbnb-base
. If we don't needReact
, we can install this package instead ofeslint-config-airbnb
-
eslint-config-airbnb-typescript
, which supports typescript and depends oneslint-config-airbnb
.
Let's first execute npm info "eslint-config-airbnb@latest" peerDependencies
to learn about the dependent package version of eslint-config-airbnb
.
npm info "eslint-config-airbnb@latest" peerDependencies
{
eslint: '^7.32.0 || ^8.2.0',
'eslint-plugin-import': '^2.25.3',
'eslint-plugin-jsx-a11y': '^6.5.1',
'eslint-plugin-react': '^7.28.0',
'eslint-plugin-react-hooks': '^4.3.0'
}
after we know the version of the dependency package, we install the corresponding version
yarn add --dev eslint-plugin-import@^2.25.3 eslint-plugin-jsx-a11y@^6.5.1 eslint-plugin-react@^7.28.0 eslint-plugin-react-hooks@^4.3.0
then install eslint-config-airbnb
and eslint-config-airbnb-typescript
yarn add --dev eslint-config-airbnb eslint-config-airbnb-typescript
follow eslint-config-airbnb-typescript configuration step , now re-adjust .eslintrc.js
file
module.exports = {
root: true,
env: {
browser: true,
node: true,
es6: true,
},
extends: ['airbnb', 'airbnb-typescript', 'airbnb/hooks', 'plugin:@typescript-eslint/recommended'],
parser: '@typescript-eslint/parser', // since eslint uses espree as the interpreter of js by default, our project uses ts, so this is replaced by this
plugins: ['@typescript-eslint'],
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
ecmaFeatures: {
jsx: true,
},
project: './tsconfig.json',
},
rule: {
'react/react-in-jsx-scope': 'off', // there is no need to actively introduce react into jsx after React17
},
};
so far, we can add the command to package.json
.
{
"script": {
"lint:js": "eslint --ext .js,.jsx,.ts,.tsx ./src"
}
}
execute yarn lint:js
to check our code quality
install prettier
execute yarn add-- dev prettier
add .prettierrc
file to the project directory, and we add commonly used formatting styles
{
"singleQuote": true, // single quotes
"trailingComma": "all", // in a multi-line comma-separated syntax structure, the last line is also added a comma
"printWidth": 100, // the maximum code width is 100.
"proseWrap": "never" // disable line wrapping in markdown text style
}
add .prettierplate
to the project directory, ignoring some files that do not need to be formatted by prettierg
**/*.png
**/*.svg
package.json
dist
.DS_Store
node_modules
so far, we can add the command to package.json
.
{
"script": {
"lint:prettier": "prettier -c --write \"src/**/*\""
}
}
execute yarn lint:prettier
format the code of our project
eslint-config-prettier and eslint-plugin-prettier
Let's first understand the division of labor between eslint and prettier. prettier is used for code formatting, and eslint configures code style and quality verification (eslint can also be responsible for code format, but prettier is more professional).
to avoid eslint and prettier conflicts, we need to install two more packages eslint-config-prettier
and eslint-plugin-prettier
.
The purpose of eslint-config-prettier
is to close all rules in eslint that are unnecessary or may conflict with prettier, so that eslint does not report errors or alarms to these rules when it detects code. For example, the eslint rule is double quotation marks, while we use single quotation marks to format code in prettier, there will be conflicts. We can see in eslint-config-prettier code that format rules such as indentation, quotation marks and so on are turned off. After closing, we can completely customize prettier to format our code without being affected by eslint.
eslint-plugin-prettier
is an ESLint plug-in. We said above that some of the eslint code format rules have been turned off. Suppose we agree to use double quotation marks in prettier rules, but typing the code in single quotation marks, I still hope to be able to give me some irregular errors or warnings in accordance with the rules of prettier. Then eslint-config-prettier
closes the rule in eslint that conflicts with prettier, and eslint-plugin-prettier
opens the rule based on prettier and reports the error to eslint.
with the above explanation, we begin to install and execute yarn add-- dev eslint-config-prettier eslint-plugin-prettier
after installation, we only need to add a line to the .eslintrc.js
file
{
extends: [
// ...
'plugin:prettier/recommended'
]
}
The role of plugin:prettier/recommende
will help us expand to the following code
{
extends: ['prettier'],
plugins: ['prettier'],
rules: {
'prettier/prettier': 'error',
'arrow-body-style': 'off',
'prefer-arrow-callback': 'off',
},
}
We can also change some rules by ourselves, such as
{
rules: {
'prettier/prettier': [
'error',
{
singleAttributePerLine: false, // an attribute is not required to occupy a row.
}
]
}
}
at this point, the configuration of eslint
and prettier
is complete. Let's take a look at the complete .eslintrc.js
file .
module.exports = {
root: true, // specify root as true,eslint to check only the current project directory
env: {
// provide default global variables to prevent eslint from checking for errors, such as window
browser: true,
node: true,
es6: true,
},
extends: [
// share the recommended configuration style
'airbnb',
'airbnb-typescript',
'airbnb/hooks',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
parser: '@typescript-eslint/parser', // since eslint uses espree as the interpreter of js by default, our project uses ts, so this is replaced by this
plugins: ['@typescript-eslint'],
parserOptions: {
ecmaVersion: 'latest', // specify the ECMAScript syntax as up-to-date
sourceType: 'module', // specify the code as ECMAScript module
ecmaFeatures: {
jsx: true, // enable jsx
},
project: './tsconfig.json',
},
rules: {
'react/react-in-jsx-scope': 'off', // there is no need to actively introduce react into jsx after React17
'prettier/prettier': [
'error',
{
singleAttributePerLine: false, // an attribute is not required to occupy a row.
}
]
},
};
install stylelint
check the quality of css-style code, in fact, many items are not detected, if you do not do this step can be ignored.
according to official website docs , we begin to install.
yarn add --dev stylelint stylelint-config-standard
add .stylelintrc.js > file to the project directory
module.exports = {
extends: ['stylelint-config-standard'],
};
We just use the official recommended stylelint-config-standard
configuration.
so far, we can add the command to package.json
.
{
"script": {
"lint:style": "stylelint \"**/*.css\""
}
}
execute yarn lint:style
to check our css code quality
similarly, we uniformly format css code with prettier. you need to install the stylelint plug-in to avoid conflicts with prettier.
-
stylelint-config-prettier
, similar toeslint-config-prettier
, is used to close all stylelint rules that are unnecessary or may conflict with prettier. However, after Stylelint v15, Stylelint turns off all style rules that conflict with prettier by default, so there is no need to installstylelint-config-prettier
. -
stylelint-prettier
, similar toeslint-plugin-prettier
, opens the rule based on prettier and reports errors to stylelint.
after learning above, we only need to install stylelint-prettier
.
install stylelint-prettier
perform installation yarn add-- dev stylelint-prettier
modify .stylelintrc.js
file
module.exports = {
extends: ['stylelint-config-standard', 'stylelint-prettier/recommended'],
};
done.
Review of code quality testing
so far our package.json
file has added three commands
{
"scripts": {
"lint:js": "eslint --ext .js,.jsx,.ts,.tsx ./src",
"lint:style": "stylelint \"**/*.css\"",
"lint:prettier": "prettier -c --write \"src/**/*\""
}
}
-
lint:js
, check js and ts code quality -
lint:style
, check css code quality -
lint:prettier
to format all code, including js, ts, css, json, md, and so on.
Note lint:prettier
just fix the code format problem.
if we want to automatically fix code quality problems, for example, if you use var
to declare variables in js code, you need to automatically fix to let
or const
. Then we can add two more commands.
{
"scripts": {
"lint:js:fix": "eslint --ext .js,.jsx,.ts,.tsx ./src --fix",
"lint:style:fix": "stylelint \"**/*.css\" --fix"
}
}
then execute the above command, which is to fix all the quality and format problems of the code for you as much as possible. According to my personal preference, I do not recommend this, just use lint:prettier
. For code quality problems, you should develop good code habits and minimize such problems. If there is a code quality problem, you can manually fix it one by one according to the error report.
install lint-staged
because the check code command is valid for the entire project code, sometimes we just want to check the code we changed and ignore the rest of the project code. We can use lint-staged
, which allows us to execute check commands that are valid only for files in the git cache.
install and execute yarn add-- dev lint-staged
then package.json
add code
{
"scripts": {
"lint-staged": "lint-staged"
},
"lint-staged": {
"**/*.css": "stylelint \"**/*.css\"",
"**/*.{js,jsx,ts,tsx}": "eslint --ext .js,.jsx,.ts,.tsx",
"**/*.{js,jsx,tsx,ts,css,md,json}": "prettier --ignore-unknown --write"
}
}
File matching rules above
{
"lint-staged": {
"**/*.css": "stylelint", // matching css files are checked with stylelint
"**/*.{js,jsx,ts,tsx}": "eslint --ext .js,.jsx,.ts,.tsx", // matching js,jsx,ts,tsx files are checked with eslint
"**/*.{js,jsx,tsx,ts,css,md,json}": "prettier --ignore-unknown --write" // match js,jsx,tsx,ts,css,md,json files uniformly with prettier format code
},
}
there is competition for the execution of these three matching rules, but it doesn't matter. As long as the stylelint or eslint first detects the error report, the matching execution will be terminated. We must correct them one by one in order to form good habits and reduce the occurrence of similar problems.
after we change the code and git add.
, we can execute yarn lint-staged
. Once the prettier formatting code is successful and the stylelint and eslint have no error output, then the lint-staged executes successfully, which means our code passes the test.
install husky
since all the previous operations need to be done manually, husky allows us to automatically execute commands when git submits.
We install and execute yarn add-- dev husky
, install official website steps
We add commands in package.json
{
"scripts": {
"prepare": "husky install"
}
}
then execute the command yarn prepare
, and husky performs initialization, and you can find that our project directory has more .husky
folders, indicating successful initialization.
then we execute
npx husky add .husky/pre-commit "npm run lint-staged"
the job is done. After that, the npm run lint-staged
command will be automatically executed when we submit the git, that is, check the code problem of the git cache. If there is a problem, lint-staged
will terminate and report an error, and the git submission will not succeed.
Note
if you use mac's Sourcetree
software (Git graphics tool) to submit code, the submission may fail. Please refer to husky official website . Add the file ~ / .huskyrc
to your computer as follows
# ~/.huskyrc
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
complete code project
at this point, even if our project is configured, let's take a look at the complete package.json
{
"name": "vite-react-ts-eslint-prettier-husky",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"lint:js": "eslint --ext .js,.jsx,.ts,.tsx ./src",
"lint:style": "stylelint \"**/*.css\"",
"lint:prettier": "prettier -c --write \"src/**/*\"",
"lint-staged": "lint-staged",
"prepare": "husky install"
},
"lint-staged": {
"**/*.css": "stylelint",
"**/*.{js,jsx,ts,tsx}": "eslint --ext .js,.jsx,.ts,.tsx",
"**/*.{js,jsx,tsx,ts,css,md,json}": "prettier --ignore-unknown --write"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"@typescript-eslint/eslint-plugin": "^5.54.1",
"@typescript-eslint/parser": "^5.54.1",
"@vitejs/plugin-react": "^3.1.0",
"eslint": "^8.35.0",
"eslint-config-airbnb": "^19.0.4",
"eslint-config-airbnb-typescript": "^17.0.0",
"eslint-config-prettier": "^8.7.0",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-prettier": "^4.2.1",
"eslint-plugin-react": "^7.28.0",
"eslint-plugin-react-hooks": "^4.3.0",
"husky": "^8.0.3",
"lint-staged": "^13.2.0",
"prettier": "^2.8.4",
"stylelint": "^15.2.0",
"stylelint-config-standard": "^30.0.1",
"stylelint-prettier": "^3.0.0",
"typescript": "^4.9.3",
"vite": "^4.1.0"
}
}
Vscode plugin
in the end, if we use vscode development, we must install ESlint, Stylelint, and Prettier plug-ins. As long as the project installs ESlint and Stylelint packages, then Vscode can report code quality problems in real time. For people with obsessive-compulsive disorder, we must want to eliminate them in time. When we develop good habits, similar problems will rarely occur. (sometimes when the problem is solved, the bonus is still there, or just close the project and reopen vscode. 😆)
The Prettier plug-in allows us to format the code at any time. Every time we type a piece of code, we will be used to shift + alt + f
code formatting. Of course, you can also configure vscode to save and format automatically.