项目中代码格式化以及团队代码风格规范

507 阅读2分钟

ESLint 与 Prettier 配合解决代码格式问题

ESLint 是一个插件, 用来对 javascript 代码做质量检测

  • 例如未使用的变量,未定义的引用,比较时使用 ===,禁止不必要的括号 等等代码质量检测
  • ESLint大大提高了团队协作的代码规范统一性,以及个人的代码质量

Prettier 的作用主要是进行代码格式化,统一代码的风格

  • Prettier 自身的规范倾向于个人 / 团队的代码风格的规范或统一,例如单引号还是双引号,每行最大长度,等号左右空格,使用 tab 还是 空格等等,将Prettier 与 ESLint 一起协同工作犹如如虎添翼。
  • ESLint 的作用是代码质量检测,Prettier 的作用则主要是代码格式化
  • ESLint 只能格式化 js/ts 文件,而 Prettier 支持多种文件

怎么配置:

  1. VsCode 插件安装两个插件 EslintPrettier - Code formatter
  2. 在项目的根目录下创建 .vscode 文件夹,注意:文件夹名字前面带 . 点❗
  3. .vscode 文件夹下,创建 settings.json 文件,用来对 当前项目进行格式化
  4. 在项目根目录下创建 .prettierrc 文件,用来对代码风格进行配置

.vscode/settings.json 文件

   {
      // eslint 保存格式化
      "eslint.enable": true,
      // 执行 eslint 检测的时间,onType 输入时
      "eslint.run": "onType",
      //指定 eslint 所处理的文件的后缀
      "eslint.options": {
        "extensions": [".js", ".ts", ".jsx", ".tsx", ".vue"]
      },
      // 编辑器保存格式化
      "editor.codeActionsOnSave": {
        "source.fixAll": true,
        "source.fixAll.eslint": true
      },
      // .ts 文件格式化程序
      "[typescript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
      },

      // .vue 文件格式化程序
      "[vue]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
      },

      "[json]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
      },

      // 操作时作为单词分隔符的字符
      "editor.wordSeparators": "`~!@#%^&*()=+[{]}\\|;:'\",.<>/?",

      // 一个制表符等于的空格数
      "editor.tabSize": 2,

      // 行尾字符
      // "files.eol": "\n",

      // 保存到额时候用使用 prettier 进行格式化
      "editor.formatOnSave": true,

      // // 不要有分号
      // "prettier.semi": false,
      // // 使用单引号
      // "prettier.singleQuote": true,
      // // 默认使用prittier作为格式化工具
      // "editor.defaultFormatter": "esbenp.prettier-vscode",
      // // 一行的字符数,如果超过会进行换行,默认为80
      // "prettier.printWidth": 200,
      // // 尾随逗号问题,设置为none 不显示 逗号
      // "prettier.trailingComma": "none"
    }

.prettierrc 文件

    {
      "semi": false,
      "singleQuote": true,
      "useTabs": false,
      "tabWidth": 2,
      "printWidth": 130,
      "trailingComma": "none",
      "endOfLine": "auto"
    }