规范统一前端代码风格

1,236 阅读5分钟

背景

众所周知,前端项目的代码质量和代码格式的校验是不可或缺的。很早之前在一个人开发的时候,脚手架生成vue项目的时候都没有打开过eslint,后面有位大佬加入,给boss说,加了个插件(eslint),有几百个bug,我快改完了。老板投来,牛皮牛皮,真牛皮的眼神😁。所以我在这篇文章中描述如何规范统一前端代码风格。

我的环境:

node:14.4.0,npm :6.14.5,编辑器是vs code

目标

  1. 不限制IDE
  2. 只需要开启 ESlint 
  3. 减少风格差异选择的争吵
  4. 全自动化,自动修复,保持原本的习惯就可以

主要用到的知识点

  1. editorConfig 编辑器配置文件
  2. Eslint 文件代码检查规范
  3. prettier
  4. lint-staged 提交到git之前进行一次代码检查
  5. husky

关于EditorConfig

  • 作用:用于解决不同运行环境,不同编辑器运行同一个项目的差异。
  • 如何生效:EditorConfig插件(我的是"EditorConfig for VS code")会在打开的文件的目录中查找名为.editorConfig的文件。然后读取文件中的属性,按先后顺序执行。
  • 代码(属性不区分大小写)

# 表明是最顶层的配置文件,发现设为true时,才会停止查找.editorconfig文件
root = true
[*]
# 编码
charset = utf-8# 设置缩进风格,tab或者空格。tab是hard tabs,space为soft tabs
indent_style = space

# 缩进的宽度
indent_size = 2# 换行符,lf、cr和crlf
end_of_line = lf# 设为true表明使文件以一个空白行结尾
insert_final_newline = true# 设为true表示会除去换行行首的任意空白字符
trim_trailing_whitespace = true

关于Eslint

ESLint 能够检测出代码中的潜在问题,解决代码质量问题。比如末尾是否空行,箭头函数是否需要括号,定义变量是否定义未使用等等。(此处使用standard规范,还有其他的,此处不细说)

   //react 安装 eslint
   eslint
   eslint-plugin-standard
   eslint-config-standard-react:standard 的规则配置包扩展
   eslint-plugin-react:支持 react 语法
   babel-eslint: 兼容ES处于实验性阶段的语法
   eslint-loader:在webpack中解析
   eslint-plugin-import:支持import
   eslint-plugin-promise:支持promise
   eslint-plugin-babel:兼容处于实验阶段的特征   
    //生成vue项目的时候选择Pick an ESLint preset Standard风格,会自动安装以下插件    
    "eslint": "^4.15.0",   
    "eslint-config-standard": "^10.2.1",   
    "eslint-friendly-formatter": "^3.0.0",   
    "eslint-loader": "^1.7.1",   
    "eslint-plugin-import": "^2.7.0",   
    "eslint-plugin-node": "^5.2.0",   
    "eslint-plugin-promise": "^3.4.0",   
    "eslint-plugin-standard": "^3.0.1",   
    "eslint-plugin-vue": "^4.0.0",
   "babel-eslint": "^8.2.1",    

安装之后,将会有.eslintrc.js和.eslintignore两个文件(没有也可以自己生成)

//.eslintrc.js 有助于强制执行某些规则,具体rule可以调整
module.exports = {  
    root: true,  
    parserOptions: {    
        parser: "babel-eslint",  
    },  
    env: {    browser: true,  },  
    extends: [    
        // consider switching to `plugin:vue/strongly-recommended` or `plugin:vue/recommended` for stricter rules.    
        "plugin:vue/essential",   
        "standard",  
    ],  
    // required to lint *.vue files  
    plugins: ["vue", "prettier"],  
    // add your custom rules here  
    rules: {    
        "prettier/prettier": "error",    
        indent: [2, 2], // 控制缩进为2
        quotes: [2, "single"], //单引号    
        "no-console": 0, //不禁用console    
        "no-debugger": 1, //禁用debugger    
        "no-var": 2, //对var警告   
        semi: 2, //强制使用分号    
        "semi-spacing": [2, { before: false, after: true }], 
        // 强制分号前后不允许空格    
        "no-irregular-whitespace": 0, //不规则的空白不允许    
        "no-trailing-spaces": 1, //一行结束后面有空格就发出警告    
        "eol-last": 0, //文件以单一的换行符结束   
        "no-unused-vars": [2, { vars: "all", args: "after-used" }], //不能有声明后未被使用的变量或参数    
        "no-underscore-dangle": 0, //标识符不能以_开头或结尾    
        // allow async-await    
        "generator-star-spacing": "off",    
        // allow debugger during development    
        "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off",  
    },
};
//.eslintignore 配置检查可忽略的文件
/build/
/config/
/dist/
/*.js

//package.json中的scripts里面增加如下命令
"lint": "eslint --ext .js,.vue src", //vue
"lint": "eslint --ext .js --ext .jsx src" // react

安装prettier

使用ESLint配合这些规范,能够检测出代码中的潜在问题,提高代码质量,但是并不能完全统一代码风格,因为这些代码规范的重点并不在代码风格上。因此还需要增加一个prettier

//安装
npm i -D prettier//调用prettier对你的代码风格进行检查
npm i -D eslint-plugin-prettier
//在.eslintrc.js的rules中添加,"prettier/prettier": "error" 
//表示被prettier标记的地方抛出错误信息{  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error"
  }
}
//借助ESLint的autofix功能,在保存代码的时候,自动将抛出error的地方进行fix。
//因为我们项目是在webpack中引入eslint-loader来启动eslint的,所以我们只要稍微修改webpack的配置,就能在启动webpack-dev-server的时候,每次保存代码同时自动对代码进行格式化。
const path = require('path')module.exports = {
  module: {
    rules: [
      {
        test: /\.(js|vue)$/,
        loader: 'eslint-loader',
        enforce: 'pre',
        include: [path.join(__dirname, 'src')],
        options: {
          fix: true
        }
      }
    ]
}//eslint和prettier冲突的情况 安装
npm i -D eslint-config-prettier
//.eslintrc.js
 extends: [    
    "standard",    
    "plugin:vue/essential",    
    "plugin:prettier/recommended",  
], 
//.prettierrc
{  
    "eslintIntegration": true,  
    "singleQuote": true,  
    "semi": false,  
    "trailingComma": "es5",  
    "endOfLine": "auto"
}

Lint-staged与husky

lint-staged:确保在暂存文件的时候能够让错误格式代码不会提交到你分支。可以定制在特定的git阶段执行特定的命令

husky:git命令hook专用配置

//安装
npm install --save-dev lint-staged husky
//package.json增加如下配置
"husky": {    "hooks": {      "pre-commit": "lint-staged"    }  },  
"lint-staged": {    "*.{js,vue,css,less,json,md}": [      "prettier --write",      "git add"    ],    "**/*.less": "stylelint --syntax less",    "**/*.{js,vue}": "npm run lint-staged:js"  }

关于行结束符

当开发过程中,有的是mac开发,有的是windows开发,那么换行符就会冲突。

// 换行符。 Mac使用 'unix' 对应 LF,Win使用 'windows' 对应 CRLF
'linebreak-style': ['error', 'unix']
//修改git全局配置,禁止git自动将lf转换成crlf, 命令:
git config --global core.autocrlf false
//修改编辑器的用户配置,例如vscode
"files.eol": "\n", // 文件换行使用lf方式

针对不同的框架的项目,大多都是相同的。只是针对不同的文件例如.vue或者.jsx有细微差别

尾声

以上是一个项目的代码错误和风格检查,以及到提交环节的配置。但是在实际中,针对不同的ide还需要增加ide的配置。

以vscode为例子:当保存文件的时候将自动格式化代码
{
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.formatOnSave": true,
}