-
Notifications
You must be signed in to change notification settings - Fork 6
Linting & Formatting
We recommend to use linters and formatters to ensure the code quality in an Angular project.
A linter statically analyzes the code against a set of rules. Examples are naming conventions, unused code or member ordering. That way, the linter ensures that the code is consistent according to these rules.
With current Angular projects, eslint is the default linter. While there are common rulesets for TypeScript and JavaScript available on the internet, there are also rulesets specifically for Angular code.
Common eslint rulesets typically also contain formatting rules such as line lengths. Since we recommend to format the code with prettier (see next section) we recommend to exclude formatting rules (or more precisely: prettier rules) from the eslint configuration. All you need to do is adding the prettier ruleset to the [eslint config](https://eslint.org/docs/latest/use/configure/:
{
...
"overrides": [
{
...
"extends": [
...
"prettier"
],
}
]
}
A formatter analyzes the code regarding formatting. Examples are line lengths, line breaks, whitespaces, brackets or single/double quotes. This helps to ensure a consistent code formatting in a development team.
We recommend using prettier as a code formatter. Prettier is an opinionated code formatter, meaning, it provides a lot of rules out-of-the-box and not too many options to tweak these rules. That way, it avoids endless discussions between developers on what the best formatting rules are.
Prettier can format most of the source files used in Angular projects such as TypeScript, HTML and stylesheets. If you need to exclude specific files or file types from prettifying, you can configure a .prettierignore file.
For stylesheets like CSS or SCSS there is a special linter named stylelint. Example rules are member ordering, unknown selectors, allowed units.
Common stylelint rulesets typically also contain formatting rules such as line lengths. Since we recommend to format the code with prettier we recommend to exclude formatting rules from the stylelint configuration. All you need to do is adding the stylelint-config-prettier ruleset to the stylelint config:
{
"extends": [
...
"stylelint-config-prettier"
],
...
}
In order to keep the code in your repository consistent according to the linting and formatting rules, the linter and formatter should be executed as part of your CI builds. If you want to get one step further and prevent bad code from being committed and hence pushed to a shared repository, you could add a commit hook. This hook will be triggered before every commit and could be configured to execute the linter and formatter. If the hook raises any errors the commit will be rejected.
An easy way to set up these commit hooks is husky. Please consult the documentation on how to configure a commit hook.