(一)全局安装eslint
npm install -g eslint
eslint -v
> v8.12.0
(一)创建react项目
create-react-app demo --template typescript
(二)项目根目录执行eslint
eslint --init
√ How would you like to use ESLint? · style
√ What type of modules does your project use? · esm
√ Which framework does your project use? · react
√ Does your project use TypeScript? · No / Yes
√ Where does your code run? · browser
√ How would you like to define a style for your project? · guide
√ Which style guide do you want to follow? · standard
√ What format do you want your config file to be in? · JavaScript
√ The style guide "standard" requires eslint@^7.12.1. You are currently using eslint@8.12.0. · Yes
√ Would you like to install them now with npm? · Yes
执行完成后package.json可以看到依赖库已经自动添加,并且已经自动创建.eslintrc.js文件
(三)添加prettier库,修改.eslintrc.js配置文件
yarn add -D prettier eslint-config-prettier eslint-plugin-prettier
//.eslintrc.js
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: ['plugin:react/recommended', 'plugin:prettier/recommended'],
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 'latest',
sourceType: 'module',
},
plugins: ['react', '@typescript-eslint'],
settings: {
react: {
version: 'detect',
},
},
}
(四)根目录创建.prettierrc.js文件,并重启vscode
module.exports = {
printWidth: 100, // 指定代码长度,超出换行
tabWidth: 4, // tab 键的宽度
useTabs: false, // 不使用tab
semi: false, // 结尾加上分号
singleQuote: true, // 使用单引号
quoteProps: 'as-needed', // 要求对象字面量属性是否使用引号包裹,(‘as-needed’: 没有特殊要求,禁止使用,'consistent': 保持一致 , preserve: 不限制,想用就用)
trailingComma: 'es5', // 确保对象的最后一个属性后有逗号
bracketSpacing: true, // 大括号有空格 { name: 'rose' }
arrowParens: 'always', // 箭头函数,单个参数添加括号
requirePragma: false, // 是否严格按照文件顶部的特殊注释格式化代码
insertPragma: false, // 是否在格式化的文件顶部插入Pragma标记,以表明该文件被prettier格式化过了
proseWrap: 'preserve', // 按照文件原样折行
htmlWhitespaceSensitivity: 'ignore', //html文件的空格敏感度,控制空格是否影响布局
endOfLine: 'auto', // 结尾 \n \r \n\r auto
jsxSingleQuote: true, // jsx 语法中使用单引号
}
(五)这里开始进行vscode配置
安装两个插件 Eslint,Prettier - Code formatter,安装完成后按F1搜索 Open Settings(JSON)并打开配置文件并覆盖。注意:初始配置较少,实际开发过程根据需要添加。
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.tabSize": 4,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.format.enable": true,
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
完成