为React Native(Expo + TypeScript)设置Eslint和Prettier配置
每个项目都需要进行设置,但每次都会忘记,因此为了个人备忘而创建
此处为JavaScript的设置。
ESLint是JavaScript的静态验证工具。使用ESLint可以更容易地发现在开发过程中容易忽略的错误,如拼写错误、分号、引号、未使用的变量或块等。
###安装
yarn add -D eslint typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-react-hooks
最初的设定是生成一个.eslintrc.js文件并进行初始化。
npx eslint --init
请在以下设定中回答问题。
√ How would you like to use ESLint? · To check syntax, find problems, and enforce code style
√ What type of modules does your project use? · JavaScript modules (import/export)
√ Which framework does your project use? · react
√ Does your project use TypeScript? · Yes
√ Where does your code run? · node
√ How would you like to define a style for your project? · prompt
√ What format do you want your config file to be in? · TypeScript
√ What style of indentation do you use? · 4
√ What quotes do you use for strings? · single
√ What line endings do you use? · unix
√ Do you require semicolons? · Yes
修改.eslintrc.js文件。
module.exports = {
env: {
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:react/recommended',
'plugin:@typescript-eslint/recommended',
'prettier',
],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
},
plugins: ['react', '@typescript-eslint', 'react-hooks'],
rules: {
indent: ['error', 2],
'linebreak-style': ['error', 'unix'],
quotes: ['error', 'single'],
semi: ['error', 'always'],
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'react/display-name': 0,
'react/prop-types': 0,
},
settings: {
react: {
version: 'detect',
},
},
};
##Prettier是什么
Prettier是一个代码格式化工具(可以帮助整理源代码)。发音为”Pritia”。
安装
yarn add -D prettier eslint-config-prettier eslint-plugin-prettier
添加.prettierrc.js文件。
module.exports = {
jsxSingleQuote: true,
singleQuote: true,
trailingComma: 'all',
printWidth: 100,
endOfLine: 'lf',
};
添加.vscode/settings.json文件
通过设置这个文件,可以方便地在按下Ctrl+s保存文件时进行代码格式化。
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
}