前端项目代码规范集成

概述

团队多人开发的项目,难免会出现代码风格不一致,而出现一些问题。统一代码风格能避免一些错误,提升开发体验,提高开发效率。

为统一代码风格,在项目中引入eslint prettier等插件,期望达到以下以下几点:

  1. 开发过程中,对不规范代码给予提示
  2. 能够对代码进行自动格式化
  3. 代码提交时,校验代码是否符合规范。

1、集成 EditorConfig 配置

EditorConfig 有助于为不同 IDE 编辑器上处理同一项目的多个开发人员维护一致的代码风格。

官网:editorconfig.org

在项目的根目录下创建 .editorconfig 文件:

js 复制代码
# Editor configuration, see http://editorconfig.org

# 表示是最顶层的 EditorConfig 配置文件
root = true

[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行

[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off
trim_trailing_whitespace = false

注意:

  • VSCode 使用 EditorConfig 需要去插件市场下载插件 EditorConfig VS Code
  • JetBrains 系列 (WebStorm、IntelliJ IDEA)则不用额外安装插件,可直接使用 EditorConfig 配置。

2、集成 ESLint 配置

官方提供了3种规范:

目前来看,公认的最好的标准是Airbnb标准。

2.1 ESlint安装:

Node.js^12.22.0^14.17.0>=16.0.0

ts 复制代码
npm i eslint -D 
or 
cnpm i eslint -D 
or 
yarn add eslint -D

yarn add typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin -D

2.2 生成配置文件:

ts 复制代码
npx eslint --init

配置文件格式可以不同,但ESLint只会使用一个配置文件,优先级如下

json 复制代码
.eslintrc.js
.eslintrc.cjs
.eslintrc.yaml
.eslintrc.yml
.eslintrc.json
package.json

在修改完代码,可以在保存的时候对代码进行修复

  • 文件 > 首选项 > 设置 ,打开settings.json文件,全局设置
  • 针对单个项目进行配置,在项目文件下新建.vscode文件夹新建setting.josn 文件

2.3 忽略指定文件和目录

指定不让ESLint去做校验,可以在根目录下创建.eslintignore文件,来告诉ESLint跳过校验

json 复制代码
*.sh
node_modules
*.md
*.woff
*.ttf
.vscode
.idea
dist
/public
/docs
.husky
.local
/bin
Dockerfile

安装vscode插件ESLint 帮助我们编写配置文件

2.4 .eslintrc.json 详细配置

json 复制代码
{
  // env:你的脚本将要运行在什么环境中
  "env": {
    "browser": true,
    "commonjs": true,
    "es2021": true
  },
  // 继承已启用的规则
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended"
  ],
  // 指定ESLint使用的解析器,默认是Espree
  "parser": "@typescript-eslint/parser",
  // 指定想要支持的 JavaScript 语言选项
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module",
    "parser": "@typescript-eslint/parser"
  },
  "plugins": ["@typescript-eslint"],
  // 启用的规则及其各自的错误级别。自定义启用或关闭一些规则
   /*
    * "off" 或 0    ==>  关闭规则
    * "warn" 或 1   ==>  打开的规则作为警告(不影响代码执行)
    * "error" 或 2  ==>  规则作为一个错误(代码不能执行,界面报错)
  */
  "rules": {
    // eslint (http://eslint.cn/docs/rules)

    // typeScript (https://typescript-eslint.io/rules)

    // vue (https://eslint.vuejs.org/rules)
  }
}

3、ESlint 集成 Prettier

Prettier 是一款强大的代码格式化工具,支持JavaScript、Typescript、Css、Scss、Less、JSX、Angular、Vue、GraphQL、JSON、Markdown等,基本上前端能用到的文件格式都可以搞定,是当下最流行的格式化工具。

官网:prettier.io/

eslint有一定修复代码格式的作用,但是还不够,需要结合prettier才能达到代码风格完全统一。

3.1 安装 Prettier

根据 prettier官方建议,Prettier 版本升级后可能会有风格变化,故应当锁定 Prettier 的版本号。

ts 复制代码
npm install prettier --save-dev

3.2 安装 eslint-plugin-prettier

ESLint插件,eslint-plugin-prettier 作为一个 ESLint的规则运行,并报告不同的单个ESLint问题。

将 prettier 的能力集成到 eslint 中。按照 prettier 的规则检查代码规范性,并进行修复。

ts 复制代码
yarn add eslint-plugin-prettier --save-dev

修改.eslintrc.json文件:

第一种方式:

ts 复制代码
//插件增加prettier
"plugins": ["react","prettier"],
//继承规则增加prettier
"extends": ["eslint:recommended","prettier"],
// 不符合 prettier 规则的代码,要进行错误提示(红线)
"rules":{
  "prettier/prettier":"error" 
},

第二种方式:

json 复制代码
//相当于上面三个操作
{
    "extends": ["eslint:recommended","plugin:prettier/recommended"]
}

注:extends的含义

  • 告诉 eslint,根据指定的规范,去检查指定类型的文件。如上例:

  • 根据 eslint:recommended + prettier 规范,去检查 js 代码。

  • 当某一类型的文件,被制定了不止1个规范,存在某些规范冲突时,后面的会覆盖掉前面的。

3.3 安装 eslint-config-prettier解决冲突(如果存在冲突)

ts 复制代码
yarn add eslint-config-prettier --save-dev

作用: 解决冲突,让所有可能会与 prettier 规则存在冲突的 eslint rule 失效,并使用 prettier 的规则进行代码检查。相当于用 prettier 的规则,覆盖掉 eslint:recommended 的部分规则。

后面 prettier 格式化,也会根据这个规则来。因此,不会再有冲突。

3.4 prettier自动格式化

自动格式化src目录下的文件,命令如下:

ts 复制代码
prettier --write 'src/**/*.{ts,js,css,jsx,html,vue,tsx}'

3.5 自定义配置

Prettier 支持多种格式的配置文件,比如 .json、.yml、yaml、.js等。可根据需要进行一些自定义配置,在根目录下创建 .prettierrc 文件

json 复制代码
{
  "printWidth": 100,  // 一行的字符数,如果超过会进行换行,默认为80
  "tabWidth": 2,  // 一个tab代表几个空格数,默认为80
  "useTabs": false,  // 是否使用tab进行缩进,默认为false,表示用空格进行缩减
  "singleQuote": true,  // 字符串是否使用单引号,默认为false,使用双引号
  "semi": true,  // 行位是否使用分号,默认为true
  "trailingComma": "none",  // 是否使用尾逗号,有三个可选值"<none|es5|all>"
  "bracketSpacing": true,  // 对象大括号直接是否有空格,默认为true,效果:{ foo: bar }
  "eslintIntegration": true,  // 开启 eslint 支持
  "arrowParens": "always", // 箭头函数,只有一个参数的时候,也需要括号
  "endOfLine": "auto", // 换行符使用
  "vueIndentScriptAndStyle": true, //  vue 文件中的 script 和 style 内不用缩进
  "htmlWhitespaceSensitivity": "strict" // 根据显示样式决定 html 要不要折行
}

【注】这里的 .prettierrc,具有格式化规则的最高优先级。

3.6 忽略特定的文件或目录

在根目录下新建 .prettierignore 文件,直接添加文件名和目录名,与.eslintignore类似,示例如下:

ts 复制代码
lua
复制代码
build/*.js
public
dist
node_modules
config
config-overrides.js
src/serviceWorker.js
prettierrc
.DS_Store
.eslintrc.json
node_modules

prettier格式化的时候会忽略该配置文件中的文件或目录

3.7 .prettierrc 详细配置

json 复制代码
{
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "singleQuote": true,
  "semi": true,
  "trailingComma": "none",
  "bracketSpacing": true,
  "eslintIntegration": true,
  "arrowParens": "always",
  "endOfLine": "auto",
  "jsxBracketSameLine": false,
  "vueIndentScriptAndStyle": true,
  "htmlWhitespaceSensitivity": "strict"
}

4、 编辑器自动格式化代码

4.1 使用编辑器快捷键,格式化代码

以 vscode 为例:

ts 复制代码
Windows: shift + alt + F

Mac: shift + option + F

默认格式化规则选择 prettier,即可完成代码格式化。

4.2 保存代码自动格式化

去设置保存自动格式化

  1. 用户是针对全局,所有项目通用;
  2. 工作区针对当前工作区,也就是当前项目生效,会在项目得根目录生成.vsecode文件夹,里面会有setting.json文件

通过在设置中配置editor.codeActionsOnSave在我们进行保存的时候自动格式化代码

点击在settings.json中编辑添加如下配置:

ts 复制代码
"editor.codeActionsOnSave": {
    "source.fixAll": true,
    "source.fixAll.eslint": true
}

表示在我们保存的时候自动执行fix操作,且使用的是eslint进行fix操作。

相关推荐
恋猫de小郭4 小时前
Flutter Zero 是什么?它的出现有什么意义?为什么你需要了解下?
android·前端·flutter
崔庆才丨静觅10 小时前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby606111 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了11 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅11 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅12 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅12 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment12 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅12 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊12 小时前
jwt介绍
前端