Frontend development has undergone rapid evolution throughout the years, introducing fresh frameworks, libraries, and tools that have streamlined the process of crafting visually appealing and user-friendly web applications. However, due to the escalating complexity of web projects, maintaining code quality, and consistency, and fostering developer collaboration have emerged as a notable challenge. This is where the robust combination of Husky, ESLint, and Prettier proves to be a lifesaver, offering an effective solution to amplify the frontend development workflow. In this comprehensive article, we will delve deep into the rationales behind utilizing this trio, the benefits it brings, and a step-by-step guide on configuring it to create a flawless development experience in general. Yeah! Let's dive right in.
1. Introduction to Husky, ESLint, and Prettier
1.1 Husky
Named after the loyal and sturdy husky dog, Husky is a Git hook manager for frontend developers mostly and developers in general. It helps enforce coding standards and prevent subpar code from being committed to a repository. By integrating Husky into your project, you can define scripts that run automatically before certain Git commands, such as committing or pushing code. This allows you to catch errors, run tests, and perform other pre-commit or pre-push tasks, ensuring that your codebase remains consistent and high-quality. Cool Right?
You should see it as a stern dog, that always barks at you when do something wrong or do not follow its rules.
1.2 ESLint
ESLint is a widely used and configurable linter tool for JavaScript. It analyzes your code statically to identify potential issues, enforce coding standards, and maintain code quality. ESLint comes with a plethora of rules that can be customized based on your project's requirements. This tool not only detects syntax errors but also enforces best practices, ensuring that your code is readable, maintainable, and follows consistent coding conventions.
1.3 Prettier
Code formatting is often a contentious topic within development teams. Prettier solves this challenge by automatically formatting your code according to a predefined style guide. It eliminates debates over coding style, ensuring that your codebase looks neat and uniform. Prettier supports various file formats and can be configured to format code as you write, creating a seamless experience for developers.
2. Why Use the Husky, ESLint, and Prettier Trio?
The combination of Husky, ESLint, and Prettier addresses several pain points in development and offers a multitude of benefits:
2.1 Code Consistency
In collaborative development environments, maintaining a consistent code style across the entire codebase can be challenging. Different developers might have varying coding styles, leading to code that is hard to read and maintain. By integrating ESLint and Prettier through Husky hooks, you can enforce a unified coding style, ensuring that all code adheres to the same set of guidelines. This consistency improves code readability and reduces confusion among developers.
2.2 Error Prevention
Detecting errors and bugs early in the development process is essential for minimizing debugging time and maintaining a high-quality codebase. The Husky, ESLint, and Prettier trio assist in error prevention by running pre-commit and pre-push scripts. ESLint's static analysis capabilities catch issues such as syntax errors, potential bugs, and adherence to coding standards. This proactive approach helps developers identify and rectify problems before they reach the repository.
2.3 Efficient Collaboration
In collaborative projects, differing coding styles can lead to unnecessary conflicts and discussions among developers. Prettier's automated code formatting and ESLint's rule enforcement eliminate the need for manual code formatting and style debates. Developers can focus on writing code and implementing features, knowing that the tools will handle formatting and standards compliance. This enhances teamwork, as the trio reduces friction and allows developers to concentrate on the creative aspects of their work.
2.4 Time Savings
Manually formatting code, identifying and fixing errors, and debating coding standards consume a considerable amount of development time. The trio of Husky, ESLint, and Prettier automates these tasks, freeing up developers to concentrate on innovation and problem-solving. With automated code formatting, time spent on adjusting code style is minimized, and the development process becomes more efficient overall.
As an illustration, consider a scenario where you wish to transition the import style from single quotes to double quotes throughout an entire legacy project to ensure uniformity. Prettier and ESLint can effectively accomplish this task on your behalf. Isn't that great?
3. Setting Up Husky, ESLint, and Prettier: A Step-by-Step Guide
In this section, we'll walk you through the process of setting up the Husky, ESLint, and Prettier trio in your frontend project. We'll cover installation, configuration, and integration with code samples to illustrate each step. Putting the Trio to Work.
3.1 Integrating ESLint
ESLint can be integrated into your project by installing it and configuring its rules. Start by installing ESLint:
# Using npm
npm install eslint --save-dev
# Using yarn
yarn add eslint --dev
Next, initialize ESLint configuration using the following command:
npx eslint --init
Subsequently, inaugurate ESLint configuration using the ensuing command:
npm init @eslint/config
This command will guide you through setting up ESLint and selecting a configuration style. You can choose between popular styles like Standard, XO and more.
After configuration, ESLint will generate a .eslintrc.cjs file with your chosen settings.
3.2 Configuring ESLint
Customizing ESLint rules is essential to align it with your project's coding standards. Open the .eslintrc.cjs file in your
project directory and modify the rules accordingly. For example:
module.exports = {
"env": {
"browser": true,
"commonjs": true,
"es2021": true,
"jest": true,
},
"extends": "standard",
"overrides": [
{
"env": {
"node": true
},
"files": [
".eslintrc.{js,cjs}"
],
"parserOptions": {
"sourceType": "script"
}
}
],
"parserOptions": {
"ecmaVersion": "latest"
},
rules: {
// Add your custom ESLint rules here
'no-console': 'warn',
'no-unused-vars': 'error',
// ...
},
}
By defining rules in your ESLint configuration, you can ensure that the codebase adheres to your desired coding conventions.
Then in your package.json file, add the following commands to your scripts:
{
//...
"scripts": {
//...
"lint": "eslint .",
"lint: fix": "eslint --fix ."
},
//...
}
Subsequently, run the lint command with npm:
npm run lint
Based on the above image, it is evident that several errors are present, particularly within a specific file that doesn't meet ESLint's criteria. Subsequently, we proceed to address these issues individually or utilize the npm run lint:fix command to potentially rectify errors that can be automatically resolved.
For issues that can be rectified, employ:
npm run lint:fix
Notably, certain software, such as CRA (Create React App) and Vite, incorporate ESLint by default, negating the need for a separate setup of ESlint. Alright, give it a try and see if you understand the idea! I hope you did. Excellent, let's proceed. Prettier next!
3.3 Automating Code Formatting with Prettier
Prettier's automatic code formatting can be integrated into your project with a few simple steps:
Install Prettier using npm or yarn:
# Using npm
npm install prettier --save-dev
# Using yarn
yarn add prettier --dev
Create a .prettierrc.js file in your project directory to define your code formatting preferences. For instance:
module.exports = {
singleQuote: true,
trailingComma: 'es5',
useTabs: false,
};
Post-installation of Prettier, add it to plugins and extends in ESLint, allowing it to complement Prettier's formatting.
Ensure the functionality of Prettier by installing the Prettier extension for VSCode.
In the settings, ensure that your default formatter is set to Prettier and enable the "format on save" feature.
And there you have it, whenever you save a file while working on a specific task, Prettier automatically performs its formatting function.
3.4 Installing Husky
Husky can be easily installed using a package manager like npm or yarn. Open your terminal and navigate to your project directory.
One thing to always note is that the concept of Husky revolves around setting up ESLint or performing linting just before or as we prepare to commit. This approach aims to prevent the contamination of the existing code style of another element by executing a pre-commit script, among other considerations. I feel that's great.
Setting up:
# Using npm
npm install husky --save-dev
# Using yarn
yarn add husky --dev
Subsequently, execute:
npx husky init
Once installed, Husky provides a simple yet powerful way to manage Git hooks.
3.5 Configuring Husky Hooks
Husky hooks are scripts that run automatically before specific Git actions. To set up a pre-commit hook that integrates ESLint and Prettier, follow these steps:
Open your project's package.json
file.
Add a husky property to define your hooks. Here's an example configuration for running ESLint and Prettier before committing:
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
}
}
here's an example of a husky pre-commit file, which would be in the generated .husky folder
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx lint-staged
In this example, lint-staged is a tool that runs linters on staged files. We can then configure lint-staged to run ESLint and Prettier.
3.6 Editor Integration
Integrating Husky, ESLint, and Prettier with your code editor enhances your development experience by providing real-time feedback. Most modern code editors support extensions or plugins for these tools. So just like is specified for prettier, earlier on. Here's how you can integrate them with popular editors:
Visual Studio Code: Install the ESLint and Prettier extensions from the Visual Studio Code marketplace. Once installed, these extensions will automatically apply linting and formatting to your code as you write.
Sublime Text: Use the SublimeLinter-eslint and SublimeLinter-contrib-prettier packages to integrate ESLint and Prettier into Sublime Text.
Atom: Install the linter-eslint and atom-prettier packages to enable linting and formatting in the Atom editor.
By integrating these tools into your code editor, you receive immediate feedback on code quality and formatting, ensuring that your code adheres to standards as you write.
4. Real-world Examples: Putting the Trio to Work
In this section, we'll explore two real-world examples to demonstrate how the Husky, ESLint, and Prettier trio enhances frontend development workflows.
4.1 Example 1: Creating a React Component
Let's consider a scenario where you're creating a React component named Button. With the Husky, ESLint, and Prettier trio in place, your workflow would look like this:
*Writing Code: * As you write the code for the Button component, ESLint provides real-time feedback on potential issues such as syntax errors, unused variables, and adherence to coding standards.
Formatting: Prettier automatically formats your code according to the defined style guide. This ensures that your code remains consistent and follows best practices.
*Pre-commit Checks: * Before committing your changes, Husky's pre-commit hook kicks in. It runs lint-staged, which in turn runs ESLint and Prettier on the staged files. Any errors or formatting issues are caught and displayed.
Committing: With clean code and proper formatting, you can confidently commit your changes, knowing that you're contributing high-quality code to the repository.
4.2 Example 2: Collaborative Project Development
Consider a larger project with multiple developers collaborating on different features. The Husky, ESLint, and Prettier trio becomes invaluable in this scenario:
Pull Requests: When developers create pull requests, the pre-commit and pre-push hooks ensure that the code adheres to coding standards. This minimizes the chances of introducing bugs or inconsistencies.
Code Reviews: During code reviews, ESLint highlights issues that reviewers can address, enhancing the review process's efficiency. Prettier-formatted code is visually consistent, making it easier for reviewers to focus on the logic and functionality.
Continuous Integration: Automated testing and continuous integration pipelines benefit from the trio as well. Code that passes pre-commit and pre-push checks is more likely to pass automated tests, reducing the chances of build failures.
5. Best Practices and Customization
Although the initial configurations offered by ESLint and Prettier are valuable, customizing them to align with your project's unique requirements is crucial. With that said, let's delve into some recommended practices and tips for customization that should unquestionably be part of your toolkit.
5.1 Choosing ESLint Rules
ESLint's extensive collection of rules can be overwhelming. When choosing rules for your project, consider the following:
Project Type: Different project types might have different requirements. For instance, a Node.js backend project might have different ESLint rules compared to a frontend project.
Team Consensus: Collaborate with your development team to define a set of rules that everyone agrees on. This ensures consistency and prevents disagreements later on.
Common Mistakes: ESLint rules can catch common mistakes and potential bugs. Prioritize rules that address issues specific to your codebase.
5.2 Tailoring Prettier Formatting
Prettier offers a wide range of formatting options that you can configure to match your team's preferences. Some customization options include:
Indentation: Set the number of spaces or tabs used for indentation.
Semicolons: Choose whether to use semicolons at the end of statements.
Line Length: Define the maximum line length before Prettier wraps lines.
Quotation Marks: Specify whether to use single or double quotes for strings.
By adjusting these formatting options, you can ensure that Prettier aligns with your project's coding standards and visual preferences.
6. Future Trends and Conclusion
As frontend development continues to evolve, tools like Husky, ESLint, and Prettier are likely to become even more integral to the development workflow. With the increasing emphasis on code quality, collaboration, and efficiency, developers will continue to seek ways to streamline their processes and deliver high-quality web applications.
I'm certain that after reading this article, you should now possess a comprehension of these three components (Eslint, Prettier, and Husky), their functions within the development journey, and the steps involved in setting them up for practical use. This understanding is what truly brings satisfaction to me in crafting this article – the act of sharing this knowledge. Do you agree? Yes lol, Fantastic!
In summary, the Husky, ESLint, and Prettier trio empower frontend developers to produce precise, clean, and faultless code. This combination establishes a benchmark for superior frontend development by upholding coding standards, identifying errors promptly, and automating code formatting. By dedicating effort to tool setup and refinement, developers can unlock project potential and contribute to the development community's advancement.
Keep on building and learning, buddy! For more similar content, do stay connected on my blog. Looking forward to your return.
Till then, Merci!👋
Useful resources I used in this article: Prettier: https://prettier.io/ ESLint: https://eslint.org/ Husky: https://www.npmjs.com/package/husky
Top comments (0)