乐闻世界logo
搜索文章和话题

How to integrate Prettier for code format checking in CI/CD pipelines?

2月21日 16:56

Prettier Integration in CI/CD Pipelines

Integrating Prettier into CI/CD pipelines ensures that all committed code follows unified formatting standards, improving code quality and team collaboration efficiency.

Git Hooks Integration

Use Husky and lint-staged to automatically format code before Git commits:

  1. Install Dependencies

    bash
    npm install --save-dev husky lint-staged prettier npx husky install npm pkg set scripts.prepare="husky install"
  2. Configure lint-staged Add to package.json:

    json
    { "lint-staged": { "*.{js,jsx,ts,tsx,json,css,scss,md}": [ "prettier --write" ] } }
  3. Create Git Hook

    bash
    npx husky add .husky/pre-commit "npx lint-staged"

CI/CD Configuration

GitHub Actions

Create .github/workflows/prettier.yml:

yaml
name: Prettier Check on: [push, pull_request] jobs: prettier: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' - run: npm install - run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,scss,md}"

GitLab CI

Add to .gitlab-ci.yml:

yaml
prettier: stage: test script: - npm install - npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,scss,md}" only: - merge_requests - main

Common Commands

  • Format Files: npx prettier --write "src/**/*.js"
  • Check Format: npx prettier --check "src/**/*.js"
  • Format All Files: npx prettier --write .
  • View Differences: npx prettier --list-different "src/**/*.js"

Best Practices

  1. Unified Team Configuration: Ensure all developers use the same Prettier configuration
  2. Automated Checking: Enforce code format checking in CI/CD
  3. Auto-Fix: Use --write option to automatically fix format issues
  4. Ignore Files: Properly configure .prettierignore to avoid unnecessary formatting
  5. Version Locking: Lock Prettier version to ensure consistency

By integrating Prettier in CI/CD, you ensure the codebase always maintains unified formatting standards, reducing format disputes during code reviews.

标签:Prettier