To enable code to be easily readable and understood by the wider team, the following formatting and linting principles should be followed.
Indentation
Proper indentation is very important to increase the readability of the code. For making the code readable, programmers should use white spaces properly. Some of the spacing conventions are given below:
- There must be a space after giving a comma between two function arguments.
- Each nested block should be properly indented and spaced.
- Proper indentation should be there at the beginning and at the end of each block in the program.
- All braces should start from a new line and the code following the end of braces also start from a new line.
ESLint
ESLint is a JavaScript and TypeScript linting tool, that means it analyses source code and identifies possible programming problems and errors. It underlines errors in red and warnings in yellow. It is very useful to cover coding styles issues.
ESLint, isn't intended to perform code style fixes automatically though. Instead, ESLint warns you about code smells. For instance, it can happen that you imported something from another file, but don't make use of the imported something in your current file.
ESLint will warn you about an unused import. In contrast to Prettier, ESLint is highly configurable, because it doesn't come with pre-configured rules.
Prettier
Prettier is an opinionated code formatter, it enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary. It is very useful to keep your code readable and make sure that the code format stays consistent when working in a team. It also supports many programming languages such as : JavaScript, TypeScript, CSS, GraphQL, JSON and much more.
We will start by installing the Prettier and ESLint extension/plugin for your editor/IDE. For instance, in VSCode you can find Prettier and ESLint extensions on the VS Code Marketplace. It might be quite similar for your IDE/editor of choice.
Install two packages which are in charge of combining Prettier and ESLint:
npm install --save-dev eslint-config-prettier eslint-plugin-prettier
Finally, set the Prettier (v6.3 or above) rules in your ESLint (v6.5.1 or above) configuration. Therefore, create an .eslintrc file in the root directory of your project and give it the following configuration:
{
"extends": ["prettier"],
"plugins" : ["prettier"],
"rules": {
"prettier/prettier": ["error"]
},
}