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

How Do I Run Prettier Only on Files That I Want to Commit?

1个答案

1

To run Prettier only on staged files (i.e., files in the Git staging area), you can use the lint-staged library in combination with the husky library. The lint-staged library allows you to run scripts exclusively on Git-staged files, while husky enables you to conveniently execute commands on various Git hooks, such as the pre-commit hook.

Step 1: Install Prettier, husky, and lint-staged

If you haven't installed Prettier yet, add it to your project:

sh
npm install --save-dev prettier

Next, install husky and lint-staged:

sh
npm install --save-dev husky lint-staged

Step 2: Configure package.json

Add the husky and lint-staged configuration to your package.json file. Here's a basic example:

json
{ // ... your other configurations "scripts": { // ... your other scripts "prepare": "husky install" }, "lint-staged": { "*.{js,jsx,ts,tsx,json,css,scss,md}": [ "prettier --write" ] }, "husky": { "hooks": { "pre-commit": "lint-staged" } } }

In this configuration:

  • lint-staged specifies a matching pattern (here, a set of file extensions) and the command to run on those files (here, prettier --write).
  • husky's pre-commit hook is configured to run lint-staged before committing.

Step 3: Activate husky

Run the following command to set up Git hooks:

sh
npx husky install

When you execute git commit, the pre-commit hook triggers and runs lint-staged, which executes the prettier --write command to format all staged files.

Note

  • When setting up husky for the first time, ensure you run npm run prepare or npx husky install to create the necessary hook scripts.
  • If you're using husky version 5 or higher, the configuration may differ; consult the latest husky documentation.

These steps will help you run Prettier exclusively on staged files, automatically formatting your code before submission.

2024年6月29日 12:07 回复

你的答案