1-环境配置-引入eslint
目标
在react项目中配置eslint,并启用保存自动格式化功能
思路
- 在项目中安装eslint
- 用eslint的init命令创建eslint配置文件
- 设置vscode的自动保存格式化
步骤
-
npm i eslint typescript -D -
在项目根目录,运行
npx eslint --init
0. 按交互提示安装相关插件
0. 它会自动生成eslint的配置文件
2在vscode中把下面这勾选,可看到报错
结果:
- 设置vscode的自动保存格式化
eslint并不能深入到jsx代码中来格式化,所以需要额外的工具。
2-环境配置-引入prettier-now
prettier-now
是prettier项目的分支,具备和prettier一样的功能,不过,它允许使用更多的配置项。在vscode的插件库中,同时有prettier-now和prettier,在安装时,请不要安装错了。
步骤
- 安装vscode插件
prettier-now - 补充配置
代码
点击设置,工作区,点击右上方
.vscode\settings.json
{
//eslint自动格式化
"eslint.enable": true,
"eslint.run": "onType",
"eslint.options": {
"extensions": [
".js",
".vue",
".jsx",
".tsx"
]
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
// 编辑器设置 - 保存时做格式化
"editor.formatOnSave": true,
// 编辑器设置 - 默认采用prettier-now做格式化
// 如果使用的是prettier,这的设置应该是 esbenp.prettier-vscode
"editor.defaultFormatter":"remimarsal.prettier-now",
// 控制缩进
"prettier.useTabs": false, // 缩进不使用tab,使用空格
"prettier.tabWidth": 2, // 缩进字节数
// 函数声明时小括号前后要加空格
// 如果你使用prettier这一项是不能做选择的,导致和eslint默认配置的冲突
// 可以在百度中搜到很多的记录: https://www.baidu.com/s?wd=prettier%20%E5%87%BD%E6%95%B0%E7%A9%BA%E6%A0%BC
"prettier.spaceBeforeFunctionParen": true,
// react的jsx让>与结束标签同行
"prettier.jsxBracketSameLine": true,
"prettier.semi": false, // 不要给语句加;
"prettier.singleQuote": true, // 采用单引号
"prettier.trailingComma": "none", // 不要尾随逗号,
"prettier.printWidth": 80, // 每行超过80列就换行
// 在.js中,写div按下tab就可以自动补全,而不需要写<div再补全
"emmet.includeLanguages": {
"javascript": "javascriptreact"
}
}
3忽略react引入
react 17之后,页面上使用jsx时,可以省略import React
在16的版本中,页面上使用jsx,必须import react
解决报错:直接抄报错红色部分设置为off,要加引号包起来
.eslintrc.js
rules: {
'no-unused-vars': 'warn',
'no-use-before-define': 'off',
'react/react-in-jsx-scope': 'off'
}