前端代码格式化规范总结

在日常开发过程中,经常会碰到代码格式化不一致的问题,还要就是 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...

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

最后

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

相关推荐
万少23 分钟前
第五款 HarmonyOS 上架作品 奇趣故事匣 来了
前端·harmonyos·客户端
OpenGL29 分钟前
Android targetSdkVersion升级至35(Android15)相关问题
前端
rzl0244 分钟前
java web5(黑马)
java·开发语言·前端
Amy.Wang1 小时前
前端如何实现电子签名
前端·javascript·html5
今天又在摸鱼1 小时前
Vue3-组件化-Vue核心思想之一
前端·javascript·vue.js
蓝婷儿1 小时前
每天一个前端小知识 Day 21 - 浏览器兼容性与 Polyfill 策略
前端
百锦再1 小时前
Vue中对象赋值问题:对象引用被保留,仅部分属性被覆盖
前端·javascript·vue.js·vue·web·reactive·ref
jingling5551 小时前
面试版-前端开发核心知识
开发语言·前端·javascript·vue.js·面试·前端框架
拾光拾趣录1 小时前
CSS 深入解析:提升网页样式技巧与常见问题解决方案
前端·css
莫空00001 小时前
深入理解JavaScript属性描述符:从数据属性到存取器属性
前端·面试