前端代码格式化规范总结

在日常开发过程中,经常会碰到代码格式化不一致的问题,还要就是 js 代码语法错误等没有及时发行改正,下面就介绍一下如何使用eslintprettierhuskylint-stagedcommitizen来规范代码格式和提高代码质量的方法。

目录

  • 准备工作
  • 代码检测
  • 代码格式化
  • Git 规范

准备工作

新建项目

新建一个测试项目。

shell 复制代码
mkdir code
cd code
npm init -y
git init

测试文件

html 复制代码
<!-- index.html -->
<div>
  <h1>Hello</h1>
  <p>Hello,code!</p>
</div>
css 复制代码
/* index.css */
body {
  width: 10px;
}
js 复制代码
// index.js
function add(a, b) {
  return a + b;
}

代码检测

这里主要是使用eslint来检测代码。

eslint 官网

安装依赖包

shell 复制代码
npm install eslint

生成配置文件

  • 安装配置
shell 复制代码
npm init @eslint/config
  • 选择类型
shell 复制代码
? How would you like to use ESLint? ...
  To check syntax only
> To check syntax and find problems
  To check syntax, find problems, and enforce code style
  • 选择模块
shell 复制代码
? What type of modules does your project use? ...
> JavaScript modules (import/export)
  CommonJS (require/exports)
  None of these
  • 选择框架
shell 复制代码
? Which framework does your project use? ...
  React
> Vue.js
  None of these
  • 是否使用 ts
shell 复制代码
? Does your project use TypeScript? >> No / Yes
  • 运行环境
shell 复制代码
? Where does your code run? ...  (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser
√ Node
  • 文件格式
shell 复制代码
? What format do you want your config file to be in? ...
> JavaScript
  YAML
  JSON
  • 安装依赖
shell 复制代码
Local ESLint installation not found.
The config that you've selected requires the following dependencies:

eslint-plugin-vue@latest eslint@latest
? Would you like to install them now? >> No / Yes
  • 选择包管理器
shell 复制代码
? Which package manager do you want to use? ...
  npm
  yarn
> pnpm

等待安装完成。

shell 复制代码
Installing eslint-plugin-vue@latest, eslint@latest
npm WARN idealTree Removing dependencies.eslint in favor of devDependencies.eslint

added 12 packages in 3s
A config file was generated, but the config file itself may not follow your linting rules.
Successfully created .eslintrc.js file in D:\code

下面是生成的配置文件。

js 复制代码
module.exports = {
  env: {
    browser: true,
    es2021: true,
  },
  extends: ["eslint:recommended", "plugin:vue/vue3-essential"],
  parserOptions: {
    ecmaVersion: "latest",
    sourceType: "module",
  },
  plugins: ["vue"],
  rules: {},
};

忽略文件.eslintignore

shell 复制代码
# /node_modules/* and /bower_components/* ignored by default
# Ignore built files except build/index.js
.eslintignore
node_modules
dist
.eslintrc.js
.prettierrc.js

shell 脚本

可以写一个简单的 shell 脚本detect.sh来检测。

shell 复制代码
#!/bin/bash

echo "代码检测工具"
if [ "$1" = "-p" ];then
  if [ "$2" ];then
    if [ -f $2 ];then
      echo "正在检测中..."
      eslint --config ".eslintrc.js" --fix $2
      echo "代码检测完毕!"
    else
      echo "文件不存在!"
    fi

  else
    echo "路径错误!"
  fi
else
  echo "命令错误!"
fi

使用方法:sh detect.sh -p {文件路径}

例如:sh detect.sh -p index.js

结果是:

shell 复制代码
代码检测工具
正在检测中...
代码检测完毕!

代码格式化

这里主要是用prettier来进行代码格式化。

prettier 官网

安装 prettier

  • 全局安装
shell 复制代码
npm i prettier -g
  • 项目安装
shell 复制代码
npm i prettier -S

配置文件

配置文件参考

js 复制代码
// .prettierrc.js
//配置文档参考:https://prettier.io/docs/en/options
module.exports = {
  printWidth: 120, // 指定打印机将换行的行长度
  tabWidth: 2, // 指定每个缩进级别的空格数
  useTabs: false, // 指定每个缩进级别的空格数
  semi: true, // 在语句末尾打印分号
  singleQuote: false, // 使用单引号而不是双引号
  quoteProps: "as-needed", // 使用单引号而不是双引号
  /**
     * "as-needed"- 仅在需要时在对象属性周围添加引号。
      "consistent"- 如果对象中至少有一个属性需要引号,则引用所有属性。
      "preserve"- 尊重对象属性中引号的输入使用。
     */
  jsxSingleQuote: false, // 在 JSX 中使用单引号而不是双引号
  trailingComma: "all", // 尽可能以多行逗号分隔的语法结构打印尾随逗号
  bracketSpacing: true, // 在对象文本的方括号之间打印空格
  bracketSameLine: false, // 在对象文本的方括号之间打印空格
  arrowParens: "always", // 将多行 HTML(HTML、JSX、Vue、Angular)元素放在最后一行的末尾,而不是单独放在下一行(不适用于自闭合元素)
  requirePragma: false, // 在唯一箭头函数参数两边加上括号
  // stdinFilepath: "", // 指定用于推断要使用的分析器的文件名
  // range-start
  // rangeStart: 0, // 向后到包含所选语句的第一行的开头
  // rangeEnd: 99999, // 转发到所选语句的末尾
  requirePragma: false, // Prettier 可以将自身限制为仅格式化文件顶部包含特殊注释(称为杂注)的文件
  insertPragma: false, // Prettier 可以将自身限制为仅格式化文件顶部包含特殊注释(称为杂注)的文件
  proseWrap: "preserve", // 默认情况下,Prettier 不会更改 markdown 文本中的换行,因为某些服务使用换行敏感的渲染器
  htmlWhitespaceSensitivity: "css", // 默认情况下,Prettier 不会更改 markdown 文本中的换行
  /**
   * css 遵循 CSS 属性的默认值;
   * strict 所有标签周围的空格(或缺少空格)被认为是重要的;
   * ignore 所有标签周围的空格(或缺少空格)被认为是微不足道的
   */
  vueIndentScriptAndStyle: false, // 是否缩进 Vue 文件中的代码和标签
  endOfLine: "lf", // 正确显示行尾, lf 仅换行;crlf 回车符 + 换行符;cr 仅回车符;auto 维护现有的行尾
  singleAttributePerLine: false, // 在 HTML、Vue 和 JSX 中每行强制使用单个属性
  parser: "html", // 指定要使用的分析器
};

忽略文件.prettierignore

shell 复制代码
# Ignore artifacts:
build
dist

# Ignore all HTML files:
*.html

常用命令

下面是根据指定的配置文件.prettierrc.jsindex.js脚本进行代码格式化。

shell 复制代码
prettier --config .prettierrc.js --write index.js

冲突解决

eslint 和 prettier 规则会发生冲突,下面是解决冲突的方法。

  • 安装
shell 复制代码
npm i eslint-config-prettier eslint-plugin-prettier -D
  • 配置

.eslintrc.js文件的extendsplugins中添加prettier即可。

js 复制代码
module.exports = {
  // ...
  extends: ["eslint:recommended", "plugin:vue/vue3-essential", "prettier"],
  plugins: ["vue", "prettier"],
  // ...
};

格式化脚本

可以写一个简单的 shell 脚本format.sh来检测。

shell 复制代码
#!/bin/bash

echo "代码格式化工具"
if [ "$1" = "-p" ];then
  if [ "$2" ];then
    if [ -f $2 ];then
      echo "正在格式化..."
      prettier --config ".prettierrc.js" --write $2
      echo "格式化完毕!"
    else
      echo "文件不存在!"
    fi

  else
    echo "路径错误!"
  fi
else
  echo "命令错误!"
fi

使用方法:sh format.sh -p {文件路径}

例如:sh format.sh -p index.js

结果是:

shell 复制代码
代码格式化工具
正在格式化...
index.js 107ms
格式化完毕!

Git 规范

运行脚本

lint-staged是一个可以在 Git 暂存区中的文件上执行脚本命令。

  • 安装
shell 复制代码
npm i lint-staged -S
  • 配置

package.json中配置。

json 复制代码
{
  //...
  "lint-staged": {
    "./src/*.{js,ts}": ["eslint --fix", "prettier --config .prettierrc.js --write"]
  }
  //...
}

钩子工具

husky是一个 Git 钩子工具,可以在 Git 事件发生时执行脚本,进行代码格式化、测试等操作。

常见钩子
  • pre-commit

在执行 Git commit 命令之前触发,用于在提交代码前进行代码检查、格式化、测试等操作。

  • commit-msg

在提交消息(commit message)被创建后,但提交操作尚未完成之前触发,用于校验提交消息的格式和内容。

  • pre-push

在执行 Git push 命令之前触发,用于在推送代码前进行额外检查、测试等操作。

husky 安装配置
  • 安装
shell 复制代码
npm i husky -S
  • 启用钩子
shell 复制代码
npm pkg set scripts.prepare="husky install"
# 或者
npx husky install

安装成功后会在package.json文件中生成以下命令。

json 复制代码
{
  //...
  "scripts": {
    "prepare": "husky install"
  }
  //...
}
  • 运行脚本
shell 复制代码
npm run prepare

安装成功后会在根目录出现一个.husky目录。

  • 创建挂钩pre-commit
shell 复制代码
npx husky add .husky/pre-commit
# 或者
npx husky add .husky/commit-msg
  • 配置代码检测
shell 复制代码
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx --no-install lint-staged

提交规范

cz-conventional-changelog是一个提交消息规范,规定了提交消息的格式和结构。

  • 安装
shell 复制代码
npm i commitizen cz-conventional-changelog -S
  • 配置

package.json中配置。

json 复制代码
{
  //...
  "scripts": {
    // ...
    "cz": "git-cz"
  },
  "config": {
    "commitizen": {
      "path": "cz-conventional-changelog"
    }
  }
  //...
}
  • 运行
shell 复制代码
git status
git add .
npm run cz

接下来就根据你的情况选择填写消息内容。

shell 复制代码
? Select the type of change that you're committing: (Use arrow keys)
> feat:     A new feature
  fix:      A bug fix
  docs:     Documentation only changes
  style:    Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
  refactor: A code change that neither fixes a bug nor adds a feature
  perf:     A code change that improves performance
  test:     Adding missing tests or correcting existing tests

接下来就会自动执行刚刚填写的脚本,执行代码检测和格式化,下面就是其中的一部分执行内容。

shell 复制代码
[STARTED] Preparing lint-staged...
[COMPLETED] Preparing lint-staged...
[STARTED] Running tasks for staged files...
[STARTED] package.json --- 11 files
[STARTED] ./src/*.{js,ts} --- 1 file
[STARTED] eslint --fix
[COMPLETED] eslint --fix
[STARTED] prettier --config .prettierrc.js --write
[COMPLETED] prettier --config .prettierrc.js --write
[COMPLETED] ./src/*.{js,ts} --- 1 file
[COMPLETED] package.json --- 11 files
[COMPLETED] Running tasks for staged files...
[STARTED] Applying modifications from tasks...
[COMPLETED] Applying modifications from tasks...

如果有问题就会报错,你更改报错的地方代码就重新提交即可。

最后

以上就是前端代码格式化规范总结的主要内容,有不足之处,请多多指正。

相关推荐
艾小码1 分钟前
为什么你的JavaScript代码总是出bug?这5个隐藏陷阱太坑了!
前端·javascript
辻戋2 小时前
从零实现React Scheduler调度器
前端·react.js·前端框架
徐同保2 小时前
使用yarn@4.6.0装包,项目是react+vite搭建的,项目无法启动,报错:
前端·react.js·前端框架
Qrun3 小时前
Windows11安装nvm管理node多版本
前端·vscode·react.js·ajax·npm·html5
中国lanwp3 小时前
全局 npm config 与多环境配置
前端·npm·node.js
JELEE.4 小时前
Django登录注册完整代码(图片、邮箱验证、加密)
前端·javascript·后端·python·django·bootstrap·jquery
TeleostNaCl6 小时前
解决 Chrome 无法访问网页但无痕模式下可以访问该网页 的问题
前端·网络·chrome·windows·经验分享
前端大卫7 小时前
为什么 React 中的 key 不能用索引?
前端
你的人类朋友7 小时前
【Node】手动归还主线程控制权:解决 Node.js 阻塞的一个思路
前端·后端·node.js
小李小李不讲道理9 小时前
「Ant Design 组件库探索」五:Tabs组件
前端·react.js·ant design