Setting up an automated workflow can greatly enhance code quality and consistency in your projects. In this guide, we’ll walk through setting up Husky, Commitlint, Prettier, and Lint-Staged to ensure your codebase is consistently formatted, follows commit message conventions, and has up-to-date dependencies after each merge.
Husky helps you manage Git hooks effortlessly, allowing for automated tasks like code quality checks to run before every commit.
Install Husky as a dev dependency using npm (we will be using npm in this article):
npm install --save-dev husky
To create a .husky directory where Git hooks will be stored, run:
npx husky init
Next, add the following script in your package.json to set up Husky when installing dependencies:
"scripts": { "prepare": "husky install" }
Commitlint ensures that all commit messages follow a consistent format, maintaining a clean commit history.
Install Commitlint along with a conventional config:
npm install --save-dev @commitlint/config-conventional @commitlint/cli
npx husky add .husky/commit-msg "npx --no-install commitlint --edit \"\""
module.exports = { extends: ['@commitlint/config-conventional'], rules: { // TODO Add Scope Enum Here // 'scope-enum': [2, 'always', ['yourscope', 'yourscope']], 'type-enum': [ 2, 'always', [ 'feat', 'fix', 'docs', 'chore', 'style', 'refactor', 'ci', 'test', 'revert', 'perf', 'vercel', ], ], }, };
Lint-Staged allows you to run scripts on staged files, and Prettier enforces a consistent style in your codebase.
Install both as dev dependencies:
npm install --save-dev lint-staged prettier
Create a .prettierrc.json file in your project root with your preferred configuration. Here’s an example:
{ "plugins": ["prettier-plugin-tailwindcss"], "printWidth": 120, "useTabs": false, "tabWidth": 2, "trailingComma": "es5", "semi": true, "singleQuote": true, "bracketSpacing": true, "arrowParens": "always", "jsxSingleQuote": false, "bracketSameLine": false, "endOfLine": "lf" }
Add the following configuration to your package.json under lint-staged:
"lint-staged": { "**/*.{js,jsx,ts,tsx}": [ "eslint --max-warnings=0", "prettier --write" ], "**/*.{html,json,css,scss,md,mdx}": [ "prettier -w" ] }
Add a pre-commit hook to run Lint-Staged:
npx husky add .husky/pre-commit "npx lint-staged"
A post-merge hook ensures that your dependencies are updated after each merge by running npm install or any package manager.
Create a post-merge hook:
npx husky add .husky/post-merge "npm install"
With this setup, your project will maintain a standardized commit message format, automatically format code, and keep dependencies up-to-date post-merge. This robust workflow will streamline collaboration and improve code quality, helping you focus on building great features.
The above is the detailed content of Enhancing Your Development Workflow with Husky, Commitlint, Prettier, and Lint-Staged. For more information, please follow other related articles on the PHP Chinese website!