react项目中配置eslint

1,184 阅读1分钟

1.环境配置-引入eslint

步骤:

  1. 在项目中安装eslint
npm i eslint -D

2.在项目根目录,运行
npx eslint --init

 2.1  按交互提示安装相关插件
 2.2  它会自动生成eslint的配置文件

3.设置vscode的自动保存格式化

代码: 在项目根目录下,补充配置文件:.vscode\settings.json,其内容如下:

{
  "eslint.run": "onType",
  "eslint.options": {
    "extensions": [".js", ".vue", ".jsx", ".tsx"]
  },
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  }
}

2-环境配置-引入prettier-now

eslint并不能深入到jsx代码中来格式化,所以需要额外的工具。

prettier-now

是prettier项目的分支,具备和prettier一样的功能,不过,它允许使用更多的配置项。在vscode的插件库中,同时有prettier-now和prettier,在安装时,请不要安装错了

步骤

  1. 安装vscode插件prettier-now
  2. 补充配置

代码

.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默认配置的冲突
  "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"
  },
}

.eslintrc.js

// rules中添加如下两行

 rules: {
    'react/react-in-jsx-scope': 'off',
    'no-use-before-define': 'off'
  }