Hey there! Are you prepared to enhance your project setup and take it to the next level? Let's begin and simplify your development process to make it more scalable and maintainable. Trust me, these quick configurations will save you a lot of time and prevent headaches in the future.
Why Bother? What's in it for You?
Before we begin, you may be wondering why you should invest your time in this., Well, my friend, think of it this way: just two minutes now can save you hours of frustration later.
By standardizing your project setup, you'll ensure smoother collaboration across your team and maintain clean, readable code effortlessly.
Reduced Errors: Automated checks catch mistakes before they become problems, saving you debugging headaches.
Improved Readability: Consistent formatting makes code easier to understand for everyone working on the project.
Easier Collaboration: Shared coding standards ensure everyone's code plays nicely together.
Future-Proofing: A well-structured project can easily adapt and grow as your needs evolve.
Getting Started: Essential Tools
Let's dive into the tools that will help you achieve code clarity and maintainability:
Prettier: This magic tool automatically formats your code according to a set of rules, ensuring consistent style and readability.
ESLint: Think of ESLint as your code coach. It analyzes your code for potential errors and stylistic issues, helping you write clean and maintainable code.
Husky: This tool acts as a pre-commit guardian, automatically running Prettier and ESLint before you commit changes. This ensures your code adheres to the project's standards before it gets merged.
VS Code Settings: By customizing your VS Code settings, you can enforce consistent formatting and linting across your entire development environment.
Let's Get Technical
1. Setting Up Prettier
Start by adding these dev dependencies to your project:
// You may use npm | yarn as well
pnpm add -D prettier-plugin-tailwindcss @ianvs/prettier-plugin-sort-imports eslint-plugin-unicorn @typescript-eslint/eslint-plugin eslint-config-prettier husky
This command will add some dev dependencies to your project.
prettier-plugin-tailwindcss
: Prettier plugin that helps format your Tailwind CSS classes.@ianvs/prettier-plugin-sort-imports
: This Prettier plugin automatically sorts your import statements.eslint-plugin-unicorn
: ESLint plugin that provides a set of rules that enforce good practices in your code, aiming to improve code readability and maintainability.@typescript-eslint/eslint-plugin
: This is a plugin that contains sets of ESLint rules specifically for TypeScript code.eslint-config-prettier
: This is a config that disables ESLint rules that conflict with Prettier. It helps to avoid situations where ESLint and Prettier fight over code formatting.husky
: Husky is a tool that can prevent badgit commit
,git push
and more by running linters on your changes. It supports all Git hooks.
Create a .prettierrc
file in your project root and paste the following configuration:
{
"endOfLine": "lf",
"semi": false,
"singleQuote": false,
"tabWidth": 2,
"printWidth": 135,
"trailingComma": "es5",
"importOrder": [
"^(react/(.*)$)|^(react$)",
"^(next/(.*)$)|^(next$)",
"<THIRD_PARTY_MODULES>",
"",
"^types$",
"^@/env(.*)$",
"^@/types/(.*)$",
"^@/config/(.*)$",
"^@/lib/(.*)$",
"^@/hooks/(.*)$",
"^@/components/ui/(.*)$",
"^@/components/(.*)$",
"^@/styles/(.*)$",
"^@/app/(.*)$",
"",
"^[./]"
],
"importOrderSeparation": false,
"importOrderSortSpecifiers": true,
"importOrderBuiltinModulesToTop": true,
"importOrderParserPlugins": ["typescript", "jsx", "decorators-legacy"],
"importOrderMergeDuplicateImports": true,
"importOrderCombineTypeAndValueImports": true,
"plugins": ["@ianvs/prettier-plugin-sort-imports", "prettier-plugin-tailwindcss"]
}
Now, let's break down what each property will do.
"endOfLine": "lf"
: This sets the line ending to be LF (Line Feed). This is the standard line ending in Unix-like systems, including Linux and macOS."semi": false
: This tells Prettier not to add semicolons at the end of every statement."singleQuote": false
: This instructs Prettier to use double quotes instead of single quotes."tabWidth": 2
: This sets the number of spaces per indentation-level to 2."printWidth": 135
: This sets the maximum line length to 135 characters. If a line exceeds this length, Prettier will wrap it."trailingComma": "es5"
: This tells Prettier to add trailing commas where valid in ES5 (ECMAScript 5)."importOrder"
: This is an array of regular expressions and special strings that dictate the order of import statements in your code."importOrderSeparation": false
: This tells Prettier not to add blank lines between import statement groups."importOrderSortSpecifiers": true
: This instructs Prettier to sort the specifiers in import statements."importOrderBuiltinModulesToTop": true
: This moves all built-in modules to the top of the import list."importOrderParserPlugins"
: This is an array of parser plugins to be used when parsing the import statements."importOrderMergeDuplicateImports": true
: This tells Prettier to merge duplicate import statements."importOrderCombineTypeAndValueImports": true
: This instructs Prettier to combine type and value imports from the same module into a single import statement."plugins"
: This is an array of additional plugins that Prettier should use. In this case, it includes a plugin for sorting imports and a plugin for handling Tailwind CSS.
Here I am using two plugins that help in sorting and ordering tailwind classes and module imports.
Now add this script to your package.json
file. This will make it prettier to format your project.
"format": "prettier --write \"**/*.{js,jsx,ts,tsx,json,css,scss,md}\""
2. Configuring ESLint
Create a .eslintrc
file in your project root and paste the following configuration:
{
"$schema": "https://json.schemastore.org/eslintrc",
"env": {
"browser": true,
"node": true
},
"root": true,
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"settings": {
"next": {
"rootDir": true
}
},
"plugins": ["react", "@typescript-eslint/eslint-plugin", "unicorn"],
"extends": ["next/core-web-vitals", "prettier", "plugin:@typescript-eslint/recommended"],
"overrides": [
{
"files": ["*.ts", "*.tsx"],
"parser": "@typescript-eslint/parser"
}
],
"rules": {
"camelcase": ["warn", { "properties": "always" }],
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/no-this-alias": "off",
"@typescript-eslint/ban-ts-comment": [
"error",
{
"ts-ignore": "allow-with-description",
"ts-nocheck": "allow-with-description"
}
],
"unicorn/filename-case": [
"error",
{
"case": "kebabCase"
}
]
}
}
Now, let's break down the configuration.
"$schema":
"https://json.schemastore.org/eslintrc
"
: This is a link to the JSON schema for an ESLint configuration file. It helps editors and tools understand the file's structure and provides autocompletion and validation."env": { "browser": true, "node": true }
: This tells ESLint that your code will run in a browser and Node.js environment, which defines global variables likewindow
orprocess
."root": true
: This tells ESLint to stop looking for other configuration files in parent folders."parserOptions": { "ecmaVersion": "latest", "sourceType": "module" }
: This sets the ECMAScript version to the latest and the source type to the module, which allows the use ofimport
andexport
statements."settings": { "next": { "rootDir": true } }
: This is a configuration specific to the Next.js framework."plugins": ["react", "@typescript-eslint/eslint-plugin", "unicorn"]
: This is an array of plugins that ESLint should use. Plugins usually provide additional rules."extends": ["next/core-web-vitals", "prettier", "plugin:@typescript-eslint/recommended"]
: This property is used to extend a list of named configurations, which sets a base set of rules."overrides": [ { "files": ["*.ts", "*.tsx"], "parser": "@typescript-eslint/parser" } ]
: This section allows you to specify configuration for specific files. Here, it's setting a different parser for TypeScript files."rules"
: This object contains the custom rules for your project. For example,"camelcase": ["warn", { "properties": "always" }]
tells ESLint to warn you when you're not using camelCase for naming.
3. Automating Checks with Husky
This will initialize husky in your project and you may now see a .husky
folder.
pnpm dlx husky-init
Create a .husky/pre-commit
file and add the following script:
pnpm format
pnpm lint
git add .
pnpm format
: This command runs theformat
script defined in yourpackage.json
file.pnpm lint
: This command runs thelint
script defined in yourpackage.json
file.git add .
: This is a Git command that stages all changed files in your current directory and its subdirectories for the next commit.
4. Standardizing VS Code Settings
Create a
.vscode
folder in your project root.Inside the
.vscode
folder, create asettings.json
file and paste the following configuration:
{
"typescript.enablePromptUseWorkspaceTsdk": true,
"editor.quickSuggestions": {
"strings": true
},
"editor.formatOnSave": true,
"editor.formatOnType": true
}
"typescript.enablePromptUseWorkspaceTsdk": true
: This is useful when you are working on a project that requires a specific version of TypeScript."editor.quickSuggestions": { "strings": true }
: It enables quick suggestions specifically for strings. This means that when you are typing a string value in your code, the editor will provide suggestions based on the existing strings in your code or any other relevant context."editor.formatOnSave": true
: This property controls whether the editor should automatically format the code when you save the file."editor.formatOnType": true
: This property controls whether the editor should automatically format the code as you type.
Now, you are good to go with your project.
Just check that everything fits well in your environment.
Run
pnpm format
to format your existing codebase.Run
pnpm lint
to check for any linting errors.Now, whenever you commit code, Husky will automatically run Prettier and ESLint, ensuring your code adheres to the project's standards.
Remember: This is just the beginning! As your project grows, you can customize these tools and rules to fit your specific needs.
Conclusion
By investing a little time upfront to configure these tools, you'll reap the benefits of clean, maintainable code for years to come. Your future self (and your fellow developers) will thank you! Think of it as future-proofing your project – a well-planned foundation makes it easier to adapt and grow as your needs evolve.
Spread the Knowledge!
Building a strong developer community relies on sharing valuable insights. If you found this guide helpful, consider sharing it on social media or within your network. It could be the key to unlocking cleaner, more maintainable code for someone else!
Need Help?
Don't be afraid to ask questions! If you encounter any errors during setup, feel free to reach out to me on Twitter / LinkedIn. I'm here to help you navigate the process and ensure your project thrives.
Happy coding!