# ESlint 规范

# 规范方案

ESLint

# package.json 脚本配置

"scripts": {
  "lint:js": "eslint --fix --ext .js,.vue src/views",
  "lint:css": "stylelint \"src/**/*.vue\" --fix",
  "lint": "vue-cli-service lint"
}

# eslint 使用

  • 安装

    • npm install eslint -D 安装到开发依赖
    • npx eslint || node ./node_modules/.bin/eslint 查看 eslint 有哪些命令或配置
    • npx eslint --init 初始化 eslint 会进入配置选项
    • npx eslint filename.js 检查 filename.js 是否符合 eslint 规范
    • npx eslint src 检查 src 下所有文件是否符合规范
  • npx 是什么 (opens new window)

  • 配置

  • 启动项目环境一直报 console 错误是怎么回事?

      1. 在配置文件的 rules 下配置 no-console :off
  • ESLint 使用 esprima 将源码解析成 AST,然后检测 AST 来判断代码是否符合规则。一开始速度输给 JSHint; ES6 发布以后,babel 为 ESLint 提供了支持,开发了 babel-eslint 让 ESLint 成为了最快支持 ES6 语法的 lint 工具。

  • JavaScript 是一个动态的弱类型语言,在开发中比较容易出错。因为没有编译程序,为了寻找 JavaScript 代码错误通常需要在执行过程中不断调试。像 ESLint 这样的可以让程序员在编码的过程中发现问题而不是在执行的过程中。

  • ESLint 存在的意义:

    • 避免低级 bug,找出可能发生的语法错误
    • 提示删除多余的代码
    • 确保代码遵循最佳实践 (airbnb style, javascript standard)
    • 统一团队的代码风格

# 项目中一些配置文件的作用

  • .eslintrc.js
  • .eslintignore
  • .editorconfig
  • prettier.config.js
  • stylelint.config.js

# 如何让 eslint 在项目中生效

  • 安装 eslint 并初始化
    • npm install eslint -D 安装到开发依赖
    • npx eslint --init 初始化 eslint 会进入配置选项生成 .eslintrc 文件
  • 安装相关插件或扩展
    • eslint-plugin-vue 插件
    • eslint-plugin-html 插件

# 如何让 stylelint 在项目中生效

  • 安装 stylelint

    • npm install stylelint -D
    • 配置 stylelint.config.js
  • 安装相关插件或扩展

    • stylelint-config-standard
    • stylelint-order

# 配置项

  • root 限定配置文件的使用范围

  • env 指定代码运行的宿主环境 --- 你就可以放心的使用它们的全局变量和属性。

  • globals 声明在代码中的自定义全局变量 --- 避免一些自插件中的变量检测报错

  • parser 指定 eslint 的解析器 --- 如果你使用的默认解析器的话,且在代码中使用了浏览器有兼容性的问题的 js 新特性,使用 webpack 编译就会出现问题,这时我们一般装最新的 eslint 或者安装是使用 babel-eslint 来解决问题。

  • parserOptions 设置解析器选项

  • extends 指定 eslint 规范

  • plugins 引用第三方的插件

    我们的项目中可能会有一些其他的文件也需要进行格式规范,比如 html, vue , react 等文件,就需要引入第三方插件

  • rules 启用额外的规则或覆盖默认的规则

# 如何在保存的时候格式化代码

  • vscode --> 左下角设置图标 ---> 右上角“设置 json” ---> 看到 vscode 的 json 格式的配置
    // vetur 配置
    "vetur.format.defaultFormatter.html": "js-beautify-html", // html 不换行
    "vetur.format.defaultFormatter.js": "vscode-typescript", // js 不换行
    "vetur.format.defaultFormatterOptions": {
    "js-beautify-html": {
        "wrap_line_length": 0, // 设置多个字符后换行 0 表示忽略
        "wrap_attributes": "auto", // html 标签属性 换行设置[auto|force|force-aligned|force-expand-multiline] ["auto"]
        "end_with_newline": false // 在文件结尾添加新行
    },
    // eslintm, stylelint 配置
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true,
      "source.fixAll.stylelint": true
    },
    "eslint.validate": [
      "javascript",
      "javascriptreact",
      "vue"
    ]