Improving the quality and formatting of the code in the TypeScript
Motivation
When working with code (especially when working in a large team), we face specific difficulties and want the code to meet the following requirements:
Follows centralized formatting
Follows clean code concepts
Follows standard conventions
To be free from errors
It isn't easy to meet the above requirements manually. However, there are exceptional utilities for this, which we will talk about below.
Tools
ESLint
ESLint is a JavaScript Code Quality Tool.
Prettier
Prettier is a code formatter. It provides consistent styling by applying your own rules that take maximum line length into account, wrapping code as needed.
Project example
For example, let's create a simple typescript project with one file.
Install Node.js (https://nodejs.org/)
Create project folder typescript-hello-world
Go to typescript-hello-world
Create an src folder
Go to src folder
Create file hello.ts
Add the code to hello.ts
const hello = (): void => {
console.log('Hello, World')
};
export {hello}
Run the "npm init -y"
Your project is ready.
![](https://webcf.waybackmachine.org/web/20210814003857/https://habrastorage.org/getpro/habr/upload_files/76e/119/8b2/76e1198b2a86c3df2bc9f21999cef43e.png)
Configuration
Add development dependencies
npm install typescript eslint prettier eslint-config-prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin -DAdd .eslintrc, .eslintignore, .prettierrc, .prettierignore files from https://github.com/kankou-aliaksei/typescript-eslint-prettier repository into root project folder
Add scripts to the package.json file
{
...
"scripts": {
...
"format": "prettier --write \"src/**/*.{ts,js}\"",
"lint": "eslint \"src/**/*.{ts,js}\" --fix"
},
...
}
Practice
The utilities are ready to use, and you can now run automatic formatting and code quality checking.
To format code run:
npm run format
After executing this command, the code will look more expressive, correspond to the regular canons, and look like this:
const hello = () => {
console.log('Hello, World');
};
export { hello };
To see the remaining inaccuracies, run:
npm run lint
Fix the remaining points (add the return type to the function) and enjoy clean code. :-)
const hello = (): void => {
console.log('Hello, World');
};
export { hello };
Conclusion
With the help of the ESLint and Prettier features, you can automate the formatting of your code, make it more expressive and accurate, correspond to specific rules, and avoid errors and bottlenecks even before uploading the code to the shared source storage.