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

How to configure lint-staged to run eslint and prettier scripts

1个答案

1

First, let me explain why we use lint-staged. In a multi-developer project, ensuring consistent code style and avoiding obvious errors is crucial. lint-staged automatically runs code inspection tools before a git commit, helping us catch issues early and standardize code style.

Step 1: Install Required npm Packages

To use lint-staged with ESLint and Prettier, first install these tools in your project. Assuming you have initialized a Node.js project with a package.json file, you can install these dependencies using npm or yarn.

bash
npm install --save-dev eslint prettier lint-staged husky

Or if you use yarn:

bash
yarn add eslint prettier lint-staged husky --dev

Step 2: Configure ESLint

Create a .eslintrc file (if not already created) to configure ESLint rules according to your project needs.

json
{ "extends": "eslint:recommended", "rules": { // Custom rules } }

Step 3: Configure Prettier

Create a .prettierrc file to define code formatting rules.

json
{ "semi": false, "singleQuote": true }

Step 4: Configure lint-staged

Add a lint-staged configuration to your package.json file. This configuration ensures that only files staged by git are checked and formatted by ESLint and Prettier.

json
{ // ...other configurations "lint-staged": { "*.{js,jsx,ts,tsx}": [ "eslint --fix", "prettier --write", "git add" ] } }

Here, we configure lint-staged to run ESLint and Prettier on all staged JavaScript and TypeScript files. eslint --fix automatically fixes fixable issues, and prettier --write formats the code.

Step 5: Configure Husky

Husky is a tool that allows us to easily use git hooks. We can leverage it to run lint-staged before committing.

Create a pre-commit hook file named pre-commit in the .husky directory and add the following content:

bash
#!/bin/sh . "$(dirname "$0")/_/husky.sh" npx lint-staged

Ensure this file has execute permissions:

bash
chmod +x .husky/pre-commit

Summary

With this configuration, every time you commit code, Husky triggers the pre-commit hook, which executes lint-staged, which in turn runs ESLint and Prettier on all staged files. This significantly reduces errors in the code and maintains consistent code style.

This is a concrete example of configuring lint-staged in a real project, and I hope it helps you understand and implement it in your project.

2024年7月25日 23:23 回复

你的答案