Lint是一种工具,可以分析源代码,并在出现错误或与团队编码约定不符时通知用户。在某些情况下,它还可以自动修复错误。

虽然已经为不同语言开发了许多种Lint,但是有些人可能遇到过以下问题。

  • 这是我第一次使用这种语言进行编码,什么被认为是这种语言的一般编码风格?
  • 我正在使用Lint的默认设置,但错误验证过程太严格。
    我想更改设置,但是更改设置会更容易忽略某些错误吗?

即使对于单一语言,也提出了各种编码约定。因此,特别是首先,确定哪些编码约定更好地遵循可能是困难的。

因此,让我们研究一下常用的开源软件上的Lint设置,看看正在使用哪种设置和编码约定。

ESLint

ESLint是JavaScript的linting实用程序。

ESLint不依赖于特定的编码约定,用户也可以自由地启用或禁用各个编码约定。从这个意义上讲,它的一个主要特点是其高度可定制性。

用户可以通过定义原始规则来灵活地设置编码标准,这些规则是ESLint中默认可用的编码规则。此外,第三方共享的着名编码约定,例如“Google JavaScript Style Guide”或“Airbnb JavaScript Style Guide”也可以重复使用。

您甚至可以在遵循这些编码约定的同时启用/禁用特定文件的特定规则。

如果您不知道要开始的设置,可以参考ESLint官方提供的“ 入门 ”指南,以使用建议的编码约定。

核心概念:

  • 配置文件:
    .eslintrc.eslintrc.js.eslintrc.yml
  • Rules:
    • “off” 或 0 - 关闭规则
    • “warn” 或 1 - 开启规则,使用警告级别的错误:warn (不会导致程序退出)
    • “error” 或 2 - 开启规则,使用错误级别的错误:error (当被触发的时候,程序会退出)

看一个例子:

  1. {
  2. "rules": {
  3. "semi": ["error", "never"],
  4. "quotes": ["error", "single"]
  5. }
  6. }

也可以写成:

  1. {
  2. "rules": {
  3. "semi": [2, "never"],
  4. "quotes": [2, "single"]
  5. }
  6. }
  • Extends:
    使用别人提供的包, 如google

    1. {
    2. "extends""google"
    3. }
  • 通过使用上述说明,用户可以轻松使用Google JavaScript样式指南中的编码约定,而无需从头开始编写设置。

  • Plugins:
    ESLint提供的默认规则涵盖了基本规则,但JavaScript可以使用的范围非常广泛。因此,您可能希望规则不在默认规则中。在这种情况下,可以在ESLint中开发自己的独立规则。为了让第三方开发自己的规则,ESLint允许使用插件。如果你在npm中搜索eslint-plugin- *,你可以找到第三方提供的大量自定义插件。
    如果ESLint的默认规则未提供您要使用的规则,则建议您查找插件。
    与可共享配置类似,它很容易设置。例如,如果要对React代码执行静态分析,可以安装名为eslint-plugin-react的插件,并使用以下设置来执行React语法特有的静态分析。
    1. {
    2. "extends": "google"
    3. "plugins": [
    4. "react"
    5. ],
    6. "rules"": {
    7. "semi": ["error", "never"],
    8. "quotes": ["error", "single"]
    9. }
    10. }

起步与安装

  1. 在项目中去使用 ```json // npm init 指令会在项目根目录下生成 package.json 文件。 npm init

// —save-dev 会把 eslint 安装到 package.json 文件中的 devDependencies 属性中,意思是只是开发阶段用到这个包,上线时就不需要这个包了。 npm install eslint —save-dev

  1. - 使用`npm run`
  2. 新增`package.json` 脚本,或者使用 `npx`命令
  3. ```javascript
  4. "scripts": {
  5. "lint": "eslint src",
  6. "lint:create": "eslint --init"
  7. }
  1. 然后使用`run`命令:
  2. ```bash
  3. npm run lint
  • 直接使用npx命令:
  1. npx eslint --init
  2. // 或者
  3. ./node_modules/.bin/eslint --init
  1. 在全局使用
    1. npm install -g eslint

ESLint初始化

配置方法使用 eslint --init方法

  1. npx eslint --init
  2. ? How would you like to use ESLint? (Use arrow keys)
  3. To check syntax only
  4. To check syntax and find problems
  5. To check syntax, find problems, and enforce code style
  6. ? What type of modules does your project use? (Use arrow keys)
  7. JavaScript modules (import/export)
  8. CommonJS (require/exports)
  9. None of these
  10. // 这里可以针对你的开发项目进行配置
  11. ? Which framework does your project use?
  12. React
  13. Vue.js
  14. None of these
  15. // 可以配置代码运行的地方,是浏览器还是Node环境?
  16. ? Where does your code run?
  17. ❯◉ Browser
  18. Node
  19. // 最张在哪里缓存
  20. ? What format do you want your config file to be in? (Use arrow keys)
  21. JavaScript
  22. YAML
  23. JSON
  24. // 成功创建了配置文件
  25. ? What format do you want your config file to be in? JavaScript
  26. Successfully created .eslintrc.js file in /Users/itheima/Downloads/Demo

配置文件.eslintrc.js

废弃的用法:.eslintrc,eslint使用配置的顺序:.eslintrc.js > .eslintrc.yaml > .eslintrc.yml > .eslintrc.json > .eslintrc > package.json

.eslintrc.js文件:

  1. module.exports = {
  2. "env": {
  3. "browser": true,
  4. "es6": true,
  5. "node": true
  6. },
  7. "extends": "eslint:recommended",
  8. "globals": {
  9. "Atomics": "readonly",
  10. "SharedArrayBuffer": "readonly"
  11. },
  12. "parserOptions": {
  13. "ecmaVersion": 2018,
  14. "sourceType": "module"
  15. },
  16. "rules": {
  17. }
  18. };

再来看看,yaml文件配置:

  1. env:
  2. browser: true
  3. es6: true
  4. node: true
  5. extends: 'eslint:recommended'
  6. globals:
  7. Atomics: readonly
  8. SharedArrayBuffer: readonly
  9. parserOptions:
  10. ecmaVersion: 2018
  11. sourceType: module
  12. rules: {}

该文件导出一个对象,对象包含属性 envextendsparserOptionspluginsrules 五个属性:

  • env:指定脚本的运行环境。每种环境都有一组特定的预定义全局变量,(如:nodejs,browser,commonjs等)中。
  • parserOptions:用于指定想要支持的JavaScript语言选项

    • ecmaVersion - 默认设置为3,5(默认), 你可以使用 6、7、8 或 9 来指定你想要使用的 ECMAScript 版本。你也可以用使用年份命名的版本号指定为 2015(同 6),2016(同 7),或 2017(同 8)或 2018(同 9)
    • sourceType - 设置为 "script" (默认) 或 "module"(如果你的代码是 ECMAScript 模块)。

      1. ecmaFeatures
      • 这是个对象,表示你想使用的额外的语言特性:
        • globalReturn - 允许在全局作用域下使用 return 语句
        • impliedStrict - 启用全局 strict mode (如果 ecmaVersion 是 5 或更高)
        • jsx - 启用 JSX
  • globals:执行代码时脚步需要访问的额外全局变量。
  • rules:开启某些规则,也可以设置规则的等级。
  • extends: 对默认规则进行扩展,可以使用Airbnb,或者Standard规则。

.eslintignore

可以在项目根目录创建,告诉ESLint忽略某些文件或者目录。相当于.gitignore都是纯文本文件。
例如

  1. # 注释,忽略文件node_modules**/.jsbuild

常见的eslintignore内容:

  1. node_modules/*
  2. **/node_modules/*
  3. dist/*
  4. /build/**
  5. /coverage/**
  6. /docs/**
  7. /jsdoc/**
  8. /templates/**
  9. /tests/bench/**
  10. /tests/fixtures/**
  11. /tests/performance/**
  12. /tmp/**
  13. /lib/rules/utils/unicode/is-combining-character.js
  14. test.js
  15. !.eslintrc.js

ESLint的使用方法

  • 本地使用方法:
    如果你想让 ESLint 成为你项目构建系统的一部分,我们建议在本地安装。你可以使用 npm:

    1. $ npm install eslint --save-dev
  • 紧接着你应该设置一个配置文件:

    1. $ ./node_modules/.bin/eslint --init
  • 之后,你可以在你项目根目录运行 ESLint:

    1. $ ./node_modules/.bin/eslint yourfile.js
  • 使用本地安装的 ESLint 时,你使用的任何插件或可分享的配置也都必须在本地安装。

  • 全局使用
    如果你想使 ESLint 适用于你所有的项目,我们建议你全局安装 ESLint。你可以使用 npm:

    1. $ npm install -g eslint
  • 紧接着你应该设置一个配置文件:

    1. $ eslint --init
  • 之后,你可以在任何文件或目录运行 ESLint:

    1. $ eslint yourfile.js

常用ESlint配置

ESLint的规范:

Standard: https://github.com/standard/eslint-config-standard

具体地址:eslintrc.json

Airbnb: https://github.com/airbnb/javascript

  1. comma逗号

    1. rules: {
    2. "comma-dangle": ["error", "never"],
    3. }
  2. Bad:

    1. var foo = {
    2. a: '123',
    3. b: '321', // wrong error
    4. }
  3. Right:

    1. var foo = {
    2. a: '123',
    3. b: '321'
    4. }
  4. quotes引号

  5. semi分号
  6. 空行
  7. 驼峰命名
  8. 日志输出
  9. 强等判断
  10. 冗余的变量
  11. 空格
    • 关键字后的空格
    • 函数名后的空格
    • 缩进

在IDE中的配置

  • 以下是vscode中插件配置:

3.Lint工具介绍 - 图1

配置文件:

  1. "eslint.alwaysShowStatus": true,
  2. "eslint.autoFixOnSave": true,
  3. "editor.formatOnSave": true,
  4. "eslint.validate": [
  5. "javascriptreact",
  6. {
  7. "language": "html",
  8. "autoFix": true
  9. },
  10. {
  11. "language": "javascript",
  12. "autoFix": true
  13. }
  14. ],
  15. "eslint.options": {
  16. "plugins": ["html"]
  17. },

快速修复配置:

打开 "editor.formatOnSave": true并且要打开eslint.validate如上面的配置,或者在UI界面里面设置。

3.Lint工具介绍 - 图2

  • 在Webstorm中的配置:

使用Configure Preferences

3.Lint工具介绍 - 图3

相比于vscode就智能很多。

实战vue项目配置

ESlint配置文件:

  1. module.exports = {
  2. root: true,
  3. env: {
  4. node: true,
  5. },
  6. extends: [
  7. 'plugin:vue/essential',
  8. '@vue/standard',
  9. ],
  10. rules: {
  11. 'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
  12. 'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
  13. semi: ['error', 'never'],
  14. },
  15. parserOptions: {
  16. parser: 'babel-eslint',
  17. },
  18. }

需要安装的VSCode插件:

  • vue(高亮语法)
  • vetur(格式化,代码规范)
  • Vue peek(组件跳转)
  • vue beautify(vue格式化)
  • Vue VSCode Snippets 和 Vue Snippets(代码提示)
  • Prettier(格式化 与 上面的Vetur其实是合作格式化)

vscode配置格式化:

  1. "eslint.validate": [
  2. "javascript",
  3. "javascriptreact",
  4. {
  5. "language": "html",
  6. "autoFix": true
  7. },
  8. {
  9. "language": "vue",
  10. "autoFix": true
  11. }
  12. ],
  13. "vetur.format.defaultFormatter.js": "prettier-eslint",
  14. // prettier
  15. "prettier.trailingComma": "es5",
  16. "prettier.semi": false,
  17. "prettier.jsxSingleQuote": true,
  18. "prettier.singleQuote": true,
  19. "prettier.eslintIntegration": true,

配置emmet:

  1. "emmet.syntaxProfiles": {
  2. "vue-html": "html",
  3. "vue": "html"
  4. },

在Vue-cli工具中,可以使用npm run lint:

  1. // bash输出
  2. npm run lint
  3. > vue-recipe@0.1.0 lint /Users/itheima/vue-demo
  4. > vue-cli-service lint
  5. DONE No lint errors found!

来执行vue cli配置好了的Lint脚本:

  1. "scripts": {
  2. "serve": "vue-cli-service serve",
  3. "build": "vue-cli-service build",
  4. "lint": "vue-cli-service lint"
  5. },

vscode中插件推荐使用: Vue, Vetur, Vue Peek, vue-beautify

实战react项目配置

使用create-react-app创建react项目:

  1. npx create-react-app my-app
  2. cd my-app
  3. npm start

如果npx命令没有,请全局安装create-react-app,使用npm install -g create-react-app

然后是安装eslint相关依赖:

  1. "devDependencies": {
  2. "eslint": "^5.16.0",
  3. "babel-eslint": "^10.0.2",
  4. "eslint-plugin-html": "^6.0.0",
  5. "eslint-plugin-react": "^7.14.2"
  6. }

配置eslint,或者使用eslint --init进行初始化:

  1. module.exports = {
  2. "env": {
  3. "browser": true,
  4. "commonjs": true,
  5. "node": true,
  6. "es6": true
  7. },
  8. "extends": [
  9. "eslint:recommended",
  10. "plugin:react/recommended"
  11. ],
  12. "globals": {
  13. "Atomics": "readonly",
  14. "SharedArrayBuffer": "readonly"
  15. },
  16. "parserOptions": {
  17. "ecmaFeatures": {
  18. "jsx": true,
  19. "arrowFunctions": true,
  20. "classes": true,
  21. "modules": true,
  22. "defaultParams": true
  23. },
  24. "ecmaVersion": 2018,
  25. "sourceType": "module"
  26. },
  27. "plugins": [
  28. "react"
  29. ],
  30. "rules": {
  31. },
  32. "settings": {
  33. "react": {
  34. "pragma": "React",
  35. "version": "latest",
  36. },
  37. },
  38. };

几点配置需要注意:

  • 安装插件:eslint-plugin-react
  • 配置extends: "plugin:react/recommended"
  • 配置settings

配置Airbnb:

  1. npm --save-dev install eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y babel-eslint

有三个依赖:

  • eslint-config-airbnb
  • eslint-plugin-import
  • eslint-plugin-jsx-a11y
  • Babel-eslint

修改项目配置:

  1. module.exports = {
  2. "env": {
  3. "browser": true,
  4. "commonjs": true,
  5. "node": true,
  6. "es6": true
  7. },
  8. // 这里有变化
  9. "extends": [
  10. "eslint:recommended",
  11. "plugin:react/recommended",
  12. "plugin:import/errors",
  13. "plugin:jsx-a11y/recommended",
  14. "airbnb"
  15. ],
  16. "globals": {
  17. "Atomics": "readonly",
  18. "SharedArrayBuffer": "readonly"
  19. },
  20. "parser": "babel-eslint",
  21. "parserOptions": {
  22. "ecmaFeatures": {
  23. "jsx": true,
  24. "arrowFunctions": true,
  25. "classes": true,
  26. "modules": true,
  27. "defaultParams": true
  28. },
  29. "ecmaVersion": 2018,
  30. "sourceType": "module"
  31. },
  32. // 这里有变化
  33. "plugins": [
  34. "react",
  35. "jsx-a11y",
  36. "import"
  37. ],
  38. "rules": {
  39. // 这里可以添加jsx-ally与import相关的自定义rules
  40. },
  41. "settings": {
  42. "react": {
  43. "pragma": "React",
  44. "version": "latest",
  45. },
  46. },
  47. };

StyleLint

官网:https://stylelint.io/

  • 安装依赖: ```bash npm install -D stylelint-config-recommended stylelint-config-standard

// yarn yarn add stylelint-config-recommended stylelint-config-standard -D

  1. - 配置忽略

// .stylelintignore 忽略stylelint检查的文件 /src/*/.css

  1. - `.stylelintrc.js`文件配置
  2. ```json
  3. module.exports = {
  4. "extends": ["stylelint-config-recommended", "stylelint-config-standard"],
  5. "rules": {
  6. "indentation": 2
  7. }
  8. }
  • vscode配置
    安装Prettier + stylelint插件,方便格式化代码。
    3.Lint工具介绍 - 图4
    配置文件:
    1. "[scss]": {
    2. "editor.formatOnSave": true
    3. },
    4. // 打开scss的validate配置
    5. "scss.validate": true,

HTMLHint

官网:https://htmlhint.io

github: https://github.com/htmlhint/HTMLHint

  • 安装依赖: ```bash npm install htmlhint —save-dev

// yarn yarn add htmlhint -D

  1. - 配置忽略

// .stylelintignore 忽略stylelint检查的文件 /src/*/.css

  1. - `.htmlhintrc`文件配置
  2. ```json
  3. /**
  4. 标签名必须小写
  5. 属性名必须小写
  6. 属性值必须放在双引号中
  7. 属性值一定不可为空
  8. 属性值一定不可重复
  9. Doctype必须是 HTML 文档的第一行
  10. 标签必须成对
  11. 标签必须自封闭
  12. 特殊字符必须
  13. ID 属性必须唯一
  14. src 属性一定不可为空
  15. title 属性必须出现在标签中
  16. img 标签必须包含 alt 属性
  17. Doctype 必须是 HTML5
  18. ID 和 Class 的命名规则必须统一
  19. 不该使用样式标签
  20. 不该使用行内样式
  21. 不该使用行内脚本
  22. 空格和制表符一定不可混合在行前
  23. ID 和 Class 一定不可使用广告关键词
  24. href 必须是绝对路径或者相对路径
  25. 属性值一定不可使用不安全字符
  26. script 标签不该使用在头部
  27. */
  28. {
  29. "tagname-lowercase": true,
  30. "attr-lowercase": true,
  31. "attr-value-double-quotes": true,
  32. "attr-value-not-empty": false,
  33. "attr-no-duplication": true,
  34. "doctype-first": true,
  35. "tag-pair": true,
  36. "empty-tag-not-self-closed": true,
  37. "spec-char-escape": true,
  38. "id-unique": true,
  39. "src-not-empty": true,
  40. "title-require": true,
  41. "alt-require": true,
  42. "doctype-html5": true,
  43. "id-class-value": "dash",
  44. "style-disabled": false,
  45. "inline-style-disabled": false,
  46. "inline-script-disabled": false,
  47. "space-tab-mixed-disabled": "space",
  48. "id-class-ad-disabled": false,
  49. "href-abs-or-rel": false,
  50. "attr-unsafe-chars": true,
  51. "head-script-disabled": true
  52. }
  • vscode配置
    安装PrettierHTMLHint插件,方便格式化代码。
    3.Lint工具介绍 - 图5
    用户配置文件:
    1. "[html]": {
    2. "editor.defaultFormatter": "esbenp.prettier-vscode"
    3. },
    4. // 打开scss的validate配置
    5. "files.associations": {
    6. "*.ext": "html"
    7. },