脚本如何批量格式化代码文件内容

wen 实用脚本 27

使用 Prettier(推荐)

安装和配置

# 全局安装
npm install -g prettier
# 或项目内安装
npm install --save-dev prettier

批量格式化命令

# 格式化所有JS文件
prettier --write "src/**/*.js"
# 格式化多种类型文件
prettier --write "src/**/*.{js,ts,jsx,tsx,json,css,md}"
# 使用配置文件
prettier --config .prettierrc --write "src/**/*.js"

.prettierrc 配置示例

{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2
}

Python 脚本批量格式化

import os
import subprocess
from pathlib import Path
def format_with_prettier(directory, extensions=['.js', '.ts', '.jsx', '.tsx', '.json', '.css', '.md']):
    """使用 Prettier 格式化目录下的所有指定类型文件"""
    for ext in extensions:
        pattern = f"**/*{ext}"
        cmd = f"prettier --write '{directory}/{pattern}'"
        subprocess.run(cmd, shell=True)
def format_code_files():
    """批量格式化代码文件的主函数"""
    # 项目根目录
    base_dir = Path(__file__).parent
    # 需要格式化的目录
    dirs_to_format = [
        base_dir / 'src',
        base_dir / 'components',
        base_dir / 'utils'
    ]
    for directory in dirs_to_format:
        if directory.exists():
            print(f"正在格式化: {directory}")
            format_with_prettier(str(directory))
    print("格式化完成!")
if __name__ == "__main__":
    format_code_files()

Bash/Shell 脚本

#!/bin/bash
# format_code.sh
# 设置颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'
# 需要格式化的文件类型
EXTENSIONS=("js" "ts" "jsx" "tsx" "json" "css" "scss" "md")
echo -e "${GREEN}开始批量格式化代码...${NC}"
# 检查 Prettier 是否安装
if ! command -v prettier &> /dev/null; then
    echo -e "${RED}错误: Prettier 未安装${NC}"
    echo "请运行: npm install -g prettier"
    exit 1
fi
# 格式化函数
format_directory() {
    local dir=$1
    local ext_pattern=""
    # 构建文件扩展名模式
    for ext in "${EXTENSIONS[@]}"; do
        if [ -z "$ext_pattern" ]; then
            ext_pattern="*.$ext"
        else
            ext_pattern="$ext_pattern,*.$ext"
        fi
    done
    echo "正在格式化: $dir"
    prettier --write "$dir/**/*.{$ext_pattern}" --ignore-path .gitignore
}
# 主逻辑
main() {
    # 默认格式化的目录
    TARGET_DIRS=("./src" "./components" "./scripts")
    # 如果提供了参数,使用参数指定的目录
    if [ $# -gt 0 ]; then
        TARGET_DIRS=("$@")
    fi
    for dir in "${TARGET_DIRS[@]}"; do
        if [ -d "$dir" ]; then
            format_directory "$dir"
        else
            echo -e "${RED}目录不存在: $dir${NC}"
        fi
    done
    echo -e "${GREEN}格式化完成!${NC}"
}
# 执行主函数
main "$@"

Node.js 脚本

// format.js
const { execSync } = require('child_process');
const path = require('path');
const fs = require('fs');
class CodeFormatter {
  constructor(options = {}) {
    this.extensions = options.extensions || ['js', 'ts', 'jsx', 'tsx', 'json', 'css', 'md'];
    this.ignoredDirs = options.ignoredDirs || ['node_modules', 'dist', 'build'];
  }
  // 获取所有需要格式化的文件
  getFiles(directory) {
    const files = [];
    const scanDir = (dir) => {
      const entries = fs.readdirSync(dir, { withFileTypes: true });
      for (const entry of entries) {
        const fullPath = path.join(dir, entry.name);
        if (entry.isDirectory()) {
          if (!this.ignoredDirs.includes(entry.name)) {
            scanDir(fullPath);
          }
        } else if (entry.isFile()) {
          const ext = path.extname(entry.name).slice(1);
          if (this.extensions.includes(ext)) {
            files.push(fullPath);
          }
        }
      }
    };
    scanDir(directory);
    return files;
  }
  // 格式化文件
  formatFiles(files) {
    if (files.length === 0) {
      console.log('没有找到需要格式化的文件');
      return;
    }
    console.log(`找到 ${files.length} 个文件需要格式化`);
    try {
      const filePattern = files.join(' ');
      execSync(`prettier --write ${filePattern}`, { stdio: 'inherit' });
      console.log('格式化完成!');
    } catch (error) {
      console.error('格式化失败:', error.message);
    }
  }
  // 执行格式化
  run(directories) {
    for (const dir of directories) {
      console.log(`扫描目录: ${dir}`);
      const files = this.getFiles(dir);
      this.formatFiles(files);
    }
  }
}
// 使用示例
const formatter = new CodeFormatter({
  extensions: ['js', 'ts', 'jsx', 'tsx'],
  ignoredDirs: ['node_modules', 'dist', '.git']
});
formatter.run(['./src', './components']);

使用 VS Code 批量格式化

创建 .vscode/settings.json:

脚本如何批量格式化代码文件内容

{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[typescript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

使用 ESLint 自动修复

# 安装 ESLint
npm install -g eslint
# 批量修复
eslint --fix "src/**/*.{js,ts,jsx,tsx}"

推荐的最佳实践

  1. 创建 package.json 脚本:

    {
    "scripts": {
     "format": "prettier --write \"src/**/*.{js,ts,jsx,tsx,json,css}\"",
     "format:check": "prettier --check \"src/**/*.{js,ts,jsx,tsx,json,css}\""
    }
    }
  2. 添加 Git Hooks (使用 husky):

    npm install --save-dev husky lint-staged

package.json

{ "lint-staged": { "*.{js,ts,jsx,tsx,json,css}": ["prettier --write"] } }


选择最适合你项目需求的方案,推荐使用 Prettier + 相应脚本组合。

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