如何编写统一代码格式化规则脚本

wen 实用脚本 27

本文目录导读:

如何编写统一代码格式化规则脚本

  1. 使用 Prettier(最推荐)
  2. ESLint + Prettier 集成
  3. 多语言格式化脚本
  4. 配置文件示例
  5. 提交前格式化(Git Hooks)
  6. 自动化格式化脚本
  7. 项目配置总结
  8. 使用建议

我来为您介绍如何编写统一代码格式化规则脚本,涵盖多种主流方式:

使用 Prettier(最推荐)

安装和配置脚本

npm install --save-dev prettier

创建配置文件 .prettierrc

{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 2,
  "useTabs": false,
  "bracketSpacing": true,
  "arrowParens": "always",
  "endOfLine": "lf",
  "jsxSingleQuote": false
}

格式化脚本 format.sh

#!/bin/bash
# 定义项目根目录
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
# 定义要格式化的目录/文件
TARGET_DIRS=("src" "test" "scripts")
# 格式化和检查
echo "Running Prettier formatting..."
# 格式化所有目标文件
npx prettier --write \
  --config "$ROOT_DIR/.prettierrc" \
  "$ROOT_DIR/{"${TARGET_DIRS[@]}"}/**/*.{js,jsx,ts,tsx,json,css,scss,md}"
# 检查未格式化文件
echo "Checking for unformatted files..."
npx prettier --check \
  --config "$ROOT_DIR/.prettierrc" \
  "$ROOT_DIR/"

ESLint + Prettier 集成

安装依赖

npm install --save-dev eslint prettier eslint-config-prettier eslint-plugin-prettier

ESLint 配置 .eslintrc.json

{
  "extends": [
    "eslint:recommended",
    "plugin:prettier/recommended"
  ],
  "plugins": ["prettier"],
  "rules": {
    "prettier/prettier": "error",
    "indent": ["error", 2],
    "linebreak-style": ["error", "unix"],
    "quotes": ["error", "single"],
    "semi": ["error", "always"],
    "no-unused-vars": "warn",
    "no-console": "warn"
  },
  "env": {
    "es6": true,
    "node": true,
    "browser": true
  },
  "parserOptions": {
    "ecmaVersion": 2022,
    "sourceType": "module"
  }
}

多语言格式化脚本

format-all.sh - 通用格式化脚本

#!/bin/bash
set -e  # 遇到错误立即退出
echo "🔍 Starting code formatting..."
# 1. JavaScript/TypeScript 文件
format_js() {
  echo "📝 Formatting JS/TS files..."
  npx prettier --write "**/*.{js,jsx,ts,tsx}"
  npx eslint --fix "**/*.{js,jsx,ts,tsx}"
}
# 2. Python 文件
format_python() {
  echo "🐍 Formatting Python files..."
  if command -v black &> /dev/null; then
    black .
  else
    echo "⚠️  Black not installed, install with: pip install black"
  fi
}
# 3. Go 文件
format_go() {
  echo "🔵 Formatting Go files..."
  gofmt -w .

package.json 脚本配置

{
  "scripts": {
    "format": "bash scripts/format.sh",
    "format:check": "prettier --check .",
    "format:fix": "prettier --write .",
    "lint": "eslint . --fix",
    "lint:check": "eslint ."
  }
}

配置文件示例

.editorconfig(编辑器通用配置)

root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.py]
indent_size = 4

.prettierrc.yaml(YAML 格式)

semi: true
trailingComma: "all"
singleQuote: true
printWidth: 120
tabWidth: 2
useTabs: false
bracketSpacing: true
arrowParens: "always"
proseWrap: "always"

提交前格式化(Git Hooks)

安装 husky 和 lint-staged

npm install --save-dev husky lint-staged

配置 .lintstagedrc.json

{
  "*.{js,jsx,ts,tsx}": [
    "eslint --fix",
    "prettier --write"
  ],
  "*.{json,md,css,scss}": [
    "prettier --write"
  ]
}

package.json 添加

{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  }
}

自动化格式化脚本

format-enhanced.sh

#!/bin/bash
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
echo -e "${BLUE}=== Code Formatting Tool ===${NC}"
# 检查依赖
check_dependencies() {
  local deps=("prettier" "eslint")
  for dep in "${deps[@]}"; do
    if ! npx --quiet "$dep" --version &> /dev/null; then
      echo -e "${RED}❌ $dep not found. Run: npm install${NC}"
      exit 1
    fi
  done
}
# 格式化并统计
format_with_stats() {
  local files_before=0
  local files_after=0
  echo -e "${YELLOW}📊 Starting formatting...${NC}"
  # 统计文件数量
  files_before=$(find . -type f \( -name "*.js" -o -name "*.ts" -o -name "*.jsx" -o -name "*.tsx" \) | wc -l)
  # 执行格式化
  npx prettier --write "**/*.{js,ts,jsx,tsx,json,css,scss,md}" 2>&1 | grep -E "^(\[warn\]|\[error\])"
  # 检查结果
  if npx prettier --check "**/*.{js,ts,jsx,tsx,json,css,scss,md}" &> /dev/null; then
    echo -e "${GREEN}✅ All files formatted successfully!${NC}"
  else
    echo -e "${RED}❌ Some files need formatting${NC}"
    exit 1
  fi
}
# 主函数
main() {
  check_dependencies
  # 显示配置信息
  echo -e "${BLUE}Using configuration:${NC}"
  cat .prettierrc.json 2>/dev/null || echo "No .prettierrc.json found"
  format_with_stats
  echo -e "${GREEN}✨ Formatting complete!${NC}"
}
main "$@"

项目配置总结

推荐项目结构

project/
├── .editorconfig
├── .prettierrc
├── .eslintrc.json
├── .prettierignore
├── .lintstagedrc.json
├── scripts/
│   ├── format.sh
│   └── format-enhanced.sh
└── package.json

.prettierignore

node_modules/
dist/
build/
coverage/
*.min.*
*.map

使用建议

  1. 团队标准化:统一配置文件并强制使用
  2. CI/CD 集成:在 CI 中运行格式检查
  3. 编辑器集成:配置编辑器自动格式化
  4. 增量应用:从新项目开始,逐步应用到旧项目

需要我详细解释某个特定部分或提供更多配置示例吗?

抱歉,评论功能暂时关闭!