Improve productivity with linters, formatters, testing, and hot-reload tools.
Welcome to the world of modern JavaScript development tools! Today we'll explore how to automate code formatting, enforce coding rules, and set up pre-commit hooks using ESLint, Prettier, and Husky. These tools are essential for maintaining a clean, consistent, and high-quality codebase.
Consistent code formatting is crucial for collaboration and readability. It ensures that every developer working on the project contributes code in a uniform style, reducing cognitive load when reviewing changes.
ESLint is a pluggable linting utility for JavaScript and TypeScript. It helps identify problematic patterns in your code and enforces style consistency.
npm install eslint --save-dev
npx eslint --init
This will create a .eslintrc.js configuration file in your project root. Common rules include enforcing semicolons, proper indentation, and disallowing dangerous patterns.
// .eslintrc.js
module.exports = {
env: {
browser: true,
es2021: true
},
extends: [
'eslint:recommended',
'plugin:react/recommended'
],
rules: {
'indent': ['error', 2],
'quotes': ['error', 'single'],
'semi': ['error', 'always']
}
}
Prettier is a popular code formatter that enforces consistent formatting with minimal configuration. It supports multiple languages and integrates well with other tools.
npm install prettier --save-dev
npx prettier --config
Create a .prettierrc file to configure formatting rules:
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true
}
Husky is a tool that simplifies setting up and managing git hooks. It allows you to run tasks before committing, ensuring code quality.
npm install husky --save-dev
npx husky init
Add a pre-commit hook that runs linters and formatters:
husky add .husky/pre-commit "
npm run lint && npm run format
"
These tools are used in production by companies like Facebook, Google, and Netflix to maintain code quality. They are essential for any serious JavaScript project.
Nodemon is an essential tool for Node.js developers that automatically restarts your server when file changes are detected. It significantly improves your development workflow by eliminating manual restarts, allowing you to focus on coding.
Install nodemon globally or locally depending on your project needs.
npm install -g nodemon
# or
npm install nodemon --save-dev
Modify your package.json scripts to use nodemon:
"scripts": {
"start": "nodemon src/index.js"
}
Create environment-specific configuration files like .env and use them with dotenv.
# Example .env
PORT=3000
NODE_ENV=development
For TypeScript projects, use ts-node-dev for hot reloading capabilities.
npm install -D ts-node-dev
# Then in package.json
"scripts": {
"dev": "ts-node-dev src/index.ts"
}
Nodemon is widely used in Continuous Integration/CD pipelines and development environments.
# Example CI script using nodemon
"scripts": {
"ci": "husky ci && lint-staged && nodemon src/test.js"
}
Question 1 of 9