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:
shnpm install --save-dev prettier
Next, install husky and lint-staged:
shnpm 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-stagedspecifies a matching pattern (here, a set of file extensions) and the command to run on those files (here,prettier --write).husky'spre-commithook is configured to runlint-stagedbefore committing.
Step 3: Activate husky
Run the following command to set up Git hooks:
shnpx 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 prepareornpx husky installto 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.