Blog>
Snippets

Automating code formatting with Prettier on commit

Use a pre-commit hook to automatically format staged JavaScript files with Prettier before they are committed.
module.exports = {
  // Hook configurations for 'husky'
  hooks: {
    // Command to run before commit is finalized
    'pre-commit': 'lint-staged',
  },
};
This is the 'husky' configuration in 'husky.config.js' or the 'husky' field in 'package.json'. It sets up 'husky' to run 'lint-staged' before each commit.
module.exports = {
  // Configuration for 'lint-staged'
  '*.js': [
    // Command that runs Prettier and formats staged JavaScript files
    'prettier --write',
    // Command that adds the changes to the commit
    'git add',
  ],
};
This is the 'lint-staged' configuration in '.lintstagedrc.js' or the 'lint-staged' field in 'package.json'. It sets up a script to automatically format JavaScript files with Prettier when they are staged for commit.
// Run these commands to set up the environment:
// Install husky and lint-staged
npm install husky lint-staged --save-dev

// Enable Git hooks managed by husky
npx husky install

// Add a 'pre-commit' hook that will trigger 'lint-staged'
npx husky add .husky/pre-commit 'npx lint-staged'
These shell commands are run in the terminal. They set up 'husky' and 'lint-staged' and add a pre-commit hook that will run 'lint-staged' to format the code.