目标
在react项目中配置eslint,并启用保存自动格式化功能
思路
- 在项目中安装eslint
- 用eslint的init命令创建eslint配置文件
- 设置vscode的自动保存格式化
步骤
-
npm i eslint typescript -D
-
在项目根目录,运行
npx eslint --init
-
按交互提示安装相关插件
- 选择是否使用 TypeScript, 选择是
-
它会自动生成eslint的配置文件
-
-
设置vscode的自动保存格式化
代码
在项目根目录下,补充配置文件:.vscode\settings.json
,其内容如下:
{
"eslint.run": "onType",
"eslint.options": {
"extensions": [".js", ".vue", ".jsx", ".tsx"]
},
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
}
复制代码
环境配置-引入prettier-now
eslint并不能深入到jsx代码中来格式化,所以需要额外的工具。
prettier-now
是prettier项目的分支,具备和prettier一样的功能,不过,它允许使用更多的配置项。在vscode的插件库中,同时有prettier-now和prettier,在安装时,请不要安装错了。
步骤
- 安装vscode插件
prettier-now
- 补充配置
代码
.vscode\settings.json
{
"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.bracketSpacing": false, // 去掉数组内部前后的空格
"prettier.semi": false, // 不要给语句加;
"prettier.singleQuote": true, // 采用单引号
"prettier.trailingComma": "none", // 不要尾随逗号,
"prettier.printWidth": 80, // 每行超过80列就换行
// 在.js中,写div按下tab就可以自动补全,而不需要写<div再补全
"emmet.includeLanguages": {
"javascript": "javascriptreact"
}
}
复制代码
\