风格指南

430 阅读11分钟

风格校验

通用

  • 在.eslintignore 和 .prettierignore忽略文件
  • 同时打开eslint和prettier保存修复,会先eslint —fix 然后在prettier —write
  • lint-staged应该先prettier然后在eslint进行校验
  • 修改.prettier.js和.eslintrc.js要重启vscode

prettier与eslint的区别

eslint属于linters工具类似还有stylelint,linters有2类规则一类是格式化规则(Formatting rules) 比如每行最大字符数 每行结尾是否加分号;

另一类是代码质量规则(Code-quality rules) 比如代码声明未使用 没有把变量挂载到全局上;prettier只有格式化规则没有代码质量规则

prettier-eslint eslint-plugin-prettier eslint-config-prettier区别

  • prettier-eslint // 是个npm module 本质是个function需要调用(不推荐使用) 可以自定义prettier规则
  • eslint-plugin-prettier // 是个eslint的插件需要配合eslint-config-prettier使用 (运行eslint —fix能够运行eslint和prettier)
  • eslint-config-prettier // 是一个eslint的配置 关闭了eslint和prettier冲突的部分(可以单独用或者和eslint-config-prettier一起使用)

解决方案:

  1. 运行 Prettier 之后,再使用 eslint --fix 格式化一把,这样把冲突的部分以 ESLint 的格式为标准覆盖掉,剩下的 warning 就都是代码质量问题了。
  2. 在配置 ESLint 的校验规则时候把和 Prettier 冲突的规则 disable 掉,然后再使用 Prettier 的规则作为校验规则。那么使用 Prettier 格式化后,使用 ESLint 校验就不会出现对前者的 warning。

总结: 也没有最好的方式,选最适合的

现在的方案(也可以prettier和eslint单独使用) 都是方案二

  • eslint-config-airbnb-base // airbnb方案
  • eslint-config-prettier // 关闭eslint中与prettier相冲突或不必要的规则(需在.eslintrc.js中extends中配置 plugin:prettier/recommended)
  • eslint-plugin-prettier // 将 Prettier 作为ESLint 规则运行,将诊断的问题作为eslint的问题报告(需在.eslintrc.js中plugins配置prettier)
  • vite-plugin-eslint // 在命令行和页面显示warning或error的overlay (可要可不要)
  • 打开vscode eslint插件 // 打开 保存时自动fix和prettier write
  • 打开vscode prettier插件 // 关闭保存时自动format
  • 打开Code Spell Checker // 将项目单词放在.vscode/settings.json 大多数包用的放在user的setting中
  • 打开 Error Lens // warning和error都会在当前行显示
  • eslint配置更改也要更改prettier配置 改完之后还要确认
  • 打开eslint保存自动修复 关闭prettier保存格式化

相关npm包

  1. eslint-config-airbnb-base // airbnb风格的eslint规则

  2. eslint-config-prettier 关闭eslint中与prettier相冲突或不必要的规则 (prettier开发)

    需在.eslintrc.js中extends中配置 plugin:prettier/recommended

  3. eslint-plugin-prettier 将 Prettier 作为ESLint 规则运行,将诊断的问题作为eslint的问题报告 (prettier开发的),但是风格格式化还是需要prettier

    好处:可以直接集成在lint中运行,不用分别运行prettier 和 eslint 命令,在使用 eslint --fix 时候,实际使用 prettier 来替代 eslint 的格式化功能

    坏处:代码会有非常多红色波浪线,性能也比直接运行prettier低

    需在.eslintrc.js中plugins配置prettier

  4. eslint-plugin-import eslint的import插件 作用:校验es6的import/export语法

  5. eslint-plugin-vue eslint的vue插件 作用:校验vue文件的js和ts(需要vue-eslint-parser 检查template的AST)

  6. vue-eslint-parser // eslint对vue的解析器 类似@babel/eslint-parser@typecript-eslint/parser 类似eslint默认的解析器Espree,

    能够解析.vue文件的template的指令和表达式,parserOptions.parser可以设置其他解析器,将script的内容给其他解析器使用

  7. @typescript-eslint/eslint-plugin // 为ts提供lint的eslint插件

    需要配合@typescript-eslint/parser并且2者版本号要保持一致

  8. stylelint-config-prettier 和eslint-config-prettier一样也是关闭和styleling相冲突或不必要的规则 (prettier开发)

  9. eslint-import-resolver-typescript // 在ts中支持es6的import/export

  10. vite-plugin-eslint 用于vite的eslint插件 和 @vue/cli-plugin-eslint的作用类似, 在命令行和页面显示warning或error的overlay,可以设置error中断服务也可以关闭vue cli3中关闭eslint检测 在vue.config.js中添加 lintOnSave:false 关闭服务器端 是否在开发环境下每次报错代码时都启用eslint验证,使用了eslint-loader来处理, 最终被@vue/cli-plugin-eslint处理, lintOnSave也可以算是vue自己实现的vscode eslint插件 vscode eslint插件会自动校验,没有太大必要关闭就行

  11. stylelint-prettier 和eslint-plugin-prettier一样也是将prettier作为stylelint的规则将诊断的问题作为stylelint的问题报告

  12. prettier-eslint Code ➡️ prettier ➡️ eslint --fix ➡️ Formatted Code 使得既用到了prettier也用到了eslint (prettier开发的)

    eslint-plugin-prettier 则是先eslint —fix 然后在执行prettier

  13. prettier-stylelint code > prettier > stylelint > formatted code 和prettier-eslint作用类似

eslint

原理: 是将我们的代码根据规定的解析器转化成为 AST 抽象语法树。之后根据我们传入配置中的各种规则对于源代码生成的 AST 语法树进行代码检查以及代码修复

tips

  • eslint可以修复错误,但是只有一部分rule能够修复
  • vscode eslint插件的作用就是实时自动检测代码规范,有问题标出红色波浪线
  • 默认只会解析es5,有很多内置规则,默认解析器Espree
  • 有些可以自动修复,有些修复方式有多种推荐用户手动选择修复
  • eslint-webpack-plugin就是解决eslint-loader存在的问题

错误级别

  • 0/off 忽略
  • 1/warn 警告
  • 2/error 报错

常用命令行

eslint --ext .js,.vue,.ts src
eslint --ext .js,.vue,.ts .  #指定文件夹或者所有文件夹(一定要指定文件类型因为默认情况是js文件如果设置了ts解析器也包括ts)
eslint "src/**/*.{js,vue}"

常见配置

  • root: true 表示配置文件在根目录

  • extends 预定义规则

    • 从 EsLint 本身的规则进行继承,比如 extends: ['eslint:recommended'] github.com/eslint/esli…
    • 从第三方的 NPM 包规则进行继承,比如 extends : ['eslint-config-airbnb'] 或者extends : ['airbnb'] 省略eslint-config-
    • 从 ESLint 的插件进行继承,比如 extends: ['plugin:react/recommended']
  • rules 自定义规则可以覆盖extends

  • plugin 插件(包含规则和导出可共享的配置) 可以简单理解为规则的合集

    plugins 属性值可以省略包名中的 eslint-plugin-前缀,如 reacteslint-plugin-react 的缩写

  • env 指定环境,可以使用预定义的全局变量 eg: document window global require

  • globals 定义全局变量(自定义) 类似ts中用*.d.ts自定义全局变量

    globals: {
        wangHaoyu: true, //表示可重写(或者writable)   "readonly"或者false,表示变量不可重写   "off",表示禁用该全局变量
      },
    
  • parser: 'vue-eslint-parser', 定义解析器

    Parser 选项简单来说就是表示我们以何种解析器来转译我们的代码。本质上,所有的解析器最终都需要讲代码转化为 espree 格式从而交给 Eslint 来检测

    先用vue-eslint-parser 解析.vue文件template,然后交给eslint-plugin-vue解析,将script内容交给@typecript-eslint/parser解析,2者最后解析的东西都交给espree格式最后交给Eslint处理

  • parserOptions 解析器的具体设置

    parserOptions: {
        parser: '@typescript-eslint/parser',
        sourceType: 'module', //或者script
        ecmaVersion: 2020,  // 或者latest
        ecmaFeatures: {
          jsx: true,  // 开启jsx
        },
      },
    
  • overrides 覆盖指定文件的规则 参考vue3源码

    // 项目中存在一些以 .test、.spec 结尾的测试文件,我们希望这些测试文件可以拥有不同的 Lint 配置规则
    overrides: [
        // *.test.js 以及 *.spec.js 结尾的文件特殊定义某些规则
        {
          files: ['*-test.js', '*.spec.js'],
          rules: {
            'no-unused-expressions': 2,
          },
        },
      ],
    ​
    
  • Processor 插件可以提供处理器。原理是将我们的非 JS 文件经过处理成为一个一个具名的代码块,最终在将这些处理后的 js 文件当作原始文件的子文件交给 EsLint 处理

    {
        "plugins": ["a-plugin"],
        "processor": "a-plugin/a-processor"  // 启用插件 a-plugin 提供的处理器 a-processor
    }
    
  • settings 共享配置

    settings: {
        'import/resolver': {
          typescript: {
            project: path.resolve(__dirname, './tsconfig.json'),
          },
        },
      },
    

使用Estree解析js,使用AST分析代码,每个规则都是一个插件

在.eslintrc.js配置文件中定义的配置优先级高于在package.json中的,可以在文件的不同目录使用不同的配置,子目录的配置会跟上层目录的配置合并直到root:true,如果有冲突子目录的将会覆盖上层目录

npm init @eslint/config // 初始并配置eslint生成.eslintrc.js

在npm上搜索 eslint-config 使用别人的规则

常见规则

'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
'no-console': process.env.NODE_ENV === 'production' ? 2 : 0,
quotes: ["warn", "double"], //必须是双引号,否则视为warn
quotes: ['error', 'single', { allowTemplateLiterals: true }], 
//第一个参数表示error类型,
//第二个参数
//"double"(默认)要求尽可能使用双引号
//"single"要求尽可能使用单引号
//"backtick"要求尽可能使用反引号
//第三个参数  表示支持单引号的同时允许模版字符串的写法
semi: "warn", //必须没有;(分号)否则视为warn  [1, "always"]
'no-undef': 2  // 未定义就引用
'no-unused-vars': 2 //定义了未使用(js中)
'@typescript-eslint/no-unused-vars': 1, //定义了未使用(ts中) 需要手动修复 可以disable或者删掉
'vue/no-unused-vars': 2  // 定义了未使用(vue中)
'no-case-declarations': 0 //switch case(建议关闭)
'no-unused-expressions': 0 //禁用没有使用的表达式(包括不能使用三元表达式)(建议关闭)
'max-len': [         // 一行最长(在prettier中配置即可,建议关闭)
      1,
      {
        code: 80,
        ignoreStrings: true,
        ignoreComments: true,
        ignoreTemplateLiterals: true,
      },
    ],
 '@typescript-eslint/no-empty-function': 0  // 不允许空函数(建议关闭)
 'spaced-comment': 1  // 在注释(//)之后要加上空格
 'no-plusplus': 0 // 不能用++  i++(建议禁用)
 'no-extra-semi': 0  // 

注释

/* eslint-disable */  #忽略全文(js中)
<!-- eslint-disable -->  #忽略(html中)    <!-- eslint-disable-next-line vue/max-attributes-per-line -->
/* eslint-enable */  #取消忽略全文
​
@ts-ignore #当行忽略
@ts-nocheck #忽略全文
@ts-check  #取消忽略全文
​

prettier

原理:将代码解析为AST然后重新组装

tips

  • prettier为代码格式化工具
  • vscode prettier插件的作用就是保存代码 自动运行npx prettier --write src/ 达到自动格式化的效果(推荐) 或者右键格式化
  • 支持多语言,如 js jsx vue flow ts html css等

与editorconfig区别

editorconfig是用来配置预定义的编辑器风格的,prettier是用来格式化代码的,一般在项目根目录设置,vscode需要安装EditorConfig for VS Code,webstorm内置支持(只需要配置好.editorconfig)

#.editorconfig
# https://editorconfig.org
root = true[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true[*.md]
insert_final_newline = false
trim_trailing_whitespace = false

常用命令行

prettier --write . '!**/*.{js,jsx,vue}'
prettier --check .  #检测是否有格式化

常见配置

  • overrides 类似eslint的overrides // 覆盖配置

    {
      "overrides": [
        {
          "files": "*.test.js",
          "options": {
            "semi": true
          }
        },
      ]
    }
    

常见规则

printWidth: 80, //只是一个指导原则不是强制的
singleQuote: true,  // 单引号
semi: true,  // 末尾分号
quoteProps: 'preserve' //对象属性的引号使用
  as-needed //仅在需要的时候使用
  consistent //有一个属性需要引号,就都需要引号
  preserve //保留用户输入的情况
trailingComma: 'all' //末尾逗号
  none //末尾没有逗号
  es5 //es5有效的地方保留
  all //在可能的地方都加上逗号
endOfLine: 'lf'  // 行末尾标识   还有  cr  crlf   auto
htmlWhitespaceSensitivity: 'strict' // html空格敏感性   还是css  ignore   默认css
vueIndentScriptAndStyle:  false  // vue文件script和style缩进

插件

用来支持不同语言,分为官方和社区插件

注释

// prettier-ignore  #忽略格式化(js)
<!-- prettier-ignore --> #忽略格式化(html)

husky(git hook工具,能够提供钩子 处理git 提交的各个阶段:pre-commit、commit-msg、pre-push)

chmod ug+x .husky/* // 增加权限

// 生成.husky文件夹
npm pkg set scripts.prepare="husky install"
npm run prepare
​

commitlint(提供提交规范和对规范的校验)

npm install --save-dev @commitlint/config-conventional @commitlint/cli  #安装依赖
#配置文件commitlint.config.js 或 .commitlintrc.js
module.exports = {
  extends: ["@commitlint/config-conventional"],
}
#添加commit-msg钩子
npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'

lint-staged(文件过滤工具,过滤出暂存区文件,只是一个平台不提供格式化功能) 依赖husky

#package.json中引入或者.lintstagedrc、lint-staged.config.js
"lint-staged": {
    "*.js": ["eslint --fix", "git add"]
  }

stylelint

vscode stylelint插件 跟vscode的eslint插件一样可以保存时候lint文件

commitizen

用来自定义commit提交规范

参考链接

简书-eslint入门学习整理

segmentfault-代码风格自动化

prettier playground

eslint playground

eslint-plugin-vue playground

TypeScript ESLint playground


js编码规范

airbnb-中文版

standard中文版

百度前端编码规范


css编码规范

styleguide

spec