eslint+prettier代码检查

876 阅读5分钟

随着前端开发越来越规范,代码规范已经成为一个标准前端开发的基本技能,并且很多的大厂对代码规范有严格要求。

很长一段时间,我们都没有太注意代码规范,至少我一直都是懵逼状态哈哈哈,今天就eslint+prettier+vscode做一次实战记录。话不多说,上干货!!!

简介

eslint:一款基于node的代码风格和语法错误检测工具包。

eslint主要进行两种规则校验:

  • 格式规则:如 key-spacing、comma-spacing 等,用来规范代码风格;
  • 质量规则:如 no-var 等,发现代码中存在的潜在 bug 或者可能会制造 bug 的地方 简单来说就是:格式规则用来使代码更好看,质量规则用来使代码符合语法规范,是从语法层面检查代码

prettier:一款自动修复代码风格和语法错误的工具包

一般情况下,eslint配合prettier使用足矣。那么问题来了,既然eslint已经可以进行代码风格规范了,还要prettier干嘛?一方面是eslint提供的格式规则有限,另一方面是prettier在代码风格方面做得更专业。参考

实现

采用eslint和prettier实现代码格式化,可以在IDE全局配置,也可以在项目中单独配置,在多人协作中一般采用项目配置,方便代码风格统一。毕竟你无法保证别人的IDE全局配置跟你的一样!

tip:本文提到的IDE均指vscode

项目配置

安装eslint

2019.1开始,TypeScirpt 官方决定全面采用 ESLint 作为代码检查的工具,不管是ES6还是TypeScript开发者,均采用eslint

yarn add eslint --dev

生成eslint配置文件

yarn eslint --init

init.jpg

一般情况下,我们选择中间的标准模式即可

然后依次选择CommonJS,React/Vue/none(根据项目类型),是否支持TypeScript,运行环境等,最后生成的配置文件如下:

image.png

测试

package.json添加命令

image.png

然后在src下新建一个ts文件,eslint就可以对ts文件进行校验了!有了语法检查,下一步我们开始美化代码风格

安装prettier

yarn add prettier --dev

添加配置文件

项目根目录下新建.prettierrc.js

module.exports = {
    // 一行最多 100 字符
    printWidth: 100,
    // 使用 2 个空格缩进
    tabWidth: 2,
    // 不使用缩进符,而使用空格
    useTabs: false,
    // 行尾需要有分号
    semi: true,
    // 使用单引号
    singleQuote: true,
    // 对象的 key 仅在必要时用引号
    quoteProps: 'as-needed',
    // jsx 不使用单引号,而使用双引号
    jsxSingleQuote: false,
    // 末尾不需要逗号
    trailingComma: 'none',
    // 大括号内的首尾需要空格
    bracketSpacing: true,
    // jsx 标签的反尖括号需要换行
    jsxBracketSameLine: false,
    // 箭头函数,只有一个参数的时候,也需要括号
    arrowParens: 'always',
    // 每个文件格式化的范围是文件的全部内容
    rangeStart: 0,
    rangeEnd: Infinity,
    // 不需要写文件开头的 @prettier
    requirePragma: false,
    // 不需要自动在文件开头插入 @prettier
    insertPragma: false,
    // 使用默认的折行标准
    proseWrap: 'preserve',
    // 根据显示样式决定 html 要不要折行
    htmlWhitespaceSensitivity: 'css',
    // 换行符使用 lf
    endOfLine: 'lf'
};

测试

package.json添加命令

image.png 运行yarn prettier就可以格式化代码了!

但是每次都要手动去格式化代码,显然是影响开发效率的,我们是不是可以让ide在保存代码的时候自动格式化呢?

保存自动格式化

在项目根目录创建.vscode/settings.json,配置以下内容:

{
  "breadcrumbs.enabled": true,
  // 显示 markdown 中英文切换时产生的特殊字符
  "editor.renderControlCharacters": true,
  // eslint 检测文件类型
  "eslint.validate": [
    {
      "language": "javascript",
      "autoFix": true
    },
    {
      "language": "typescript",
      "autoFix": true
    },
    {
      "language": "javascriptreact",
      "autoFix": true
    },
    {
      "language": "typescriptreact",
      "autoFix": true
    },
    {
      "language": "html",
      "autoFix": true
    }
  ],
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": true,
    "source.fixAll.eslint": true
  },
  "eslint.format.enable": true,
  "explorer.confirmDelete": false,
  "gitlens.gitCommands.skipConfirmations": ["fetch:command", "switch:command", "fetch:menu"],
  "explorer.confirmDragAndDrop": false,
  "editor.wordWrap": "on",
  "git.autofetch": true,
  "editor.formatOnSaveMode": "file",
  "files.autoSaveDelay": 10000,
  "terminal.integrated.fontFamily": "monospace",
  "files.associations": {
    "*.jsx": "javascriptreact",
    "*.tsx": "typescriptreact"
  },
  // "[typescriptreact]": {
  //     "editor.defaultFormatter": "esbenp.prettier-vscode"
  // },
  // "[scss]": {
  //     "editor.defaultFormatter": "esbenp.prettier-vscode"
  // },
  // "[typescript]": {
  //     "editor.defaultFormatter": "vscode.typescript-language-features",
  //     "editor.formatOnSave": true
  // },
  // "[javascript]": {
  //     "editor.defaultFormatter": "vscode.typescript-language-features",
  //     "editor.formatOnSave": true
  // },
  // "[jsonc]": {
  //     "editor.defaultFormatter": "vscode.json-language-features"
  // },
  // "[css]": {
  //     "editor.defaultFormatter": "sibiraj-s.vscode-scss-formatter"
  // },
  // "[html]": {
  //     "editor.defaultFormatter": "vscode.html-language-features"
  // },
  // "[json]": {
  //     "editor.defaultFormatter": "esbenp.prettier-vscode"
  // },
  // "[javascriptreact]": {
  //     "editor.defaultFormatter": "esbenp.prettier-vscode"
  // },
  "workbench.startupEditor": "welcomePage",
  "editor.largeFileOptimizations": false,
  "typescript.tsdk": "node_modules/typescript/lib"
}

tips:

  1. 新版vscode对editor.autoFormatOnSave进行了统一配置

image.png

  1. "terminal.integrated.fontFamily": "monospace"配置时是不能保存自动格式化的

全局配置

安装插件

首先,我们需要在vscode中安装eslint和prettier插件

eslint.jpg

prettier.jpg

然后我们只需要在 Code > Preferences > settings 打开setting.json 中添加刚才在项目settings.json中的规则配置即可,如:

{
  "breadcrumbs.enabled": true,
  // 显示 markdown 中英文切换时产生的特殊字符
  "editor.renderControlCharacters": true,
  // eslint 检测文件类型
  "eslint.validate": [
    {
      "language": "javascript",
      "autoFix": true
    },
    {
      "language": "typescript",
      "autoFix": true
    },
    {
      "language": "javascriptreact",
      "autoFix": true
    },
    {
      "language": "typescriptreact",
      "autoFix": true
    },
    {
      "language": "html",
      "autoFix": true
    }
  ],
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll": true,
    "source.fixAll.eslint": true
  },
  "eslint.format.enable": true,
  "explorer.confirmDelete": false,
  "gitlens.gitCommands.skipConfirmations": ["fetch:command", "switch:command", "fetch:menu"],
  "explorer.confirmDragAndDrop": false,
  "editor.wordWrap": "on",
  "git.autofetch": true,
  "editor.formatOnSaveMode": "modifications",
  "files.autoSaveDelay": 10000,
  "terminal.integrated.fontFamily": "file",
  "files.associations": {
    "*.jsx": "javascriptreact",
    "*.tsx": "typescriptreact"
  },
  // "[typescriptreact]": {
  //     "editor.defaultFormatter": "esbenp.prettier-vscode"
  // },
  // "[scss]": {
  //     "editor.defaultFormatter": "esbenp.prettier-vscode"
  // },
  // "[typescript]": {
  //     "editor.defaultFormatter": "vscode.typescript-language-features",
  //     "editor.formatOnSave": true
  // },
  // "[javascript]": {
  //     "editor.defaultFormatter": "vscode.typescript-language-features",
  //     "editor.formatOnSave": true
  // },
  // "[jsonc]": {
  //     "editor.defaultFormatter": "vscode.json-language-features"
  // },
  // "[css]": {
  //     "editor.defaultFormatter": "sibiraj-s.vscode-scss-formatter"
  // },
  // "[html]": {
  //     "editor.defaultFormatter": "vscode.html-language-features"
  // },
  // "[json]": {
  //     "editor.defaultFormatter": "esbenp.prettier-vscode"
  // },
  // "[javascriptreact]": {
  //     "editor.defaultFormatter": "esbenp.prettier-vscode"
  // },
  "workbench.startupEditor": "welcomePage",
  "editor.largeFileOptimizations": false,
  "typescript.tsdk": "node_modules/typescript/lib"
}

注意:全局配置需要重启vscode才能生效

好了,有eslint代码检测可以规范我们的开发,固然是好事,但是有时候又会觉得这个代码检测是个累赘,特别是多人协作开发时,如果每个人采用的eslint规则都不一样,合并代码时产生的冲突足以让你怀疑人生。最后我们就介绍一下如果关闭eslint代码检测。

在vscode中,我们可以这样关闭。Code > Preferences > settings 打开setting.json,设置

"eslint.enable": false

如果想要关闭项目中的eslint,我们拿react项目举例

第一步,弹出CRA内置的项目配置

yarn eject

第二步,修改package.json的eslintConfig

"eslintConfig": {
    "extends": "react-app",
    "rules": {
      "no-undef": "off",
      "no-restricted-globals": "off",
      "no-unused-vars": "off"
    }
}

关掉所有rules,然后重启项目,将不会再有eslint检测