Usually linters can validate and fix code formatting but there are specialized tools that work better.
Code consistency helps when several people work on the same codebase:
Code formatting tools solve the first problem. They also solve another problem — arguments on the right code style in a team.
Linters can help with the second problem, although they won’t solve it entirely. This like var
v. const
/ let
can be detected by ESLint, but higher level patterns can’t.
Problems like naming consistency are hard, or even impossible, to detect automatically. For example, you could have FooLoader
and BarThatLoadsFoo
that both do the same thing but in different ways. To detect such issues you’ll have to review all new code manually.
A common misconception is that if you use a code formatter like Prettier then you don’t need a linter anymore. There’s some overlap between two tools. ESLint can fix indentation, semicolons or quote type in JavaScript, but Prettier can achieve 100% code consistency, because it removes the original formatting and reprints all the code using its own formatting rules.
Most of the time you’ll benefit from using both tools at the same time: use ESLint to catch possible errors and achieve consistent language usage and Prettier to format the code.
EditorConfig allows you to define indentation style and other whitespace settings for any file type. This way your editor can automatically choose the correct settings. This is handy when developers use platforms with different line endings, e.g., Mac and Windows.
Here is a typical config (.editorconfig) with separate rules for Markdown, JSON and YAML files:
.editorconfig
root = true
[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{json,yml,md}]
indent_style = space
indent_size = 2
EditorConfig is supported by popular IDEs and editors through plugins.
It’s possible to force line endings through .gitattributes by setting* text=auto
andbin/* eol=lf
but EditorConfig has more options.
Use Mrm to add EditorConfig to your project with a single command.
Prettier is an opinionated code formatter that supports JavaScript, TypeScript, CSS, GraphQL, JSON and Markdown. It has few settings and most of the code style rules are built in. Prettier removes any existing formatting from your code and prints its own version which makes code absolutely consistent.
Prettier is smarter than other tools. For example, you can restrict line length while tools like ESLint can only yell at you if a line is too long and you would have to reformat the code yourself. If any line exceeds the limit, Prettier reformats the whole code block:
foo(wowJs(), suchFunction(), muchParameters(), shouldReformat());
After the code goes through Prettier, you’ll end up with the code below:
foo(
wowJs(),
suchFunction(),
muchParameters(),
shouldReformat()
);
However, shorter statement would be printed as one line:
foo('coffee', 'croissant', 'toast', 'eggs');
Try Prettier in an interactive playground.
This approach has many benefits:
Prettier has few options to modify its behavior, like indentation, quotes and semicolons.
You’ll need to disable code style rules in your ESLint config, otherwise they may conflict with Prettier. eslint-config-prettier will do that for any preset. eslint:recommended will work fine because it has no code style rules.
To make your contributors’ life easier you can set up Prettier to format code before each commit with lint-staged — see the Automation chapter.
Let’s install Prettier:
npm install prettier --save-dev
Prettier team recommends pinning an exact version of Prettier in your package.json as they may introduce stylistic changes in patch releases.
Add a script to your package.json like this:
package.json
{
"scripts": {
"format": "prettier --write '**/*.{js,css,md}'"
}
}
Create a config file, .prettierrc:
.prettierrc
{
"printWidth": 100,
"singleQuote": true,
"trailingComma": "es5"
}
And finally run:
npm run format
Commit your code before running Prettier for the first time — it will reformat all your codebase.
Prettier will ignore node_modules
by default, use .prettierignore file to ignore other files.
Use Mrm to add Prettier to your project with a single command.
You can also run Prettier as a ESLint plugin. This way Prettier formats all files that go through ESLint and you will not need to setup another script.
Let’s install Prettier and eslint-plugin-prettier
, assuming you already have ESLint configured as described in the Linting chapter:
npm install prettier eslint-plugin-prettier --save-dev
Update your ESLint config like this:
.eslintrc.json
{
"plugins": ["prettier"],
"rules": {
"prettier/prettier": [
"error",
{
"printWidth": 100,
"singleQuote": true,
"trailingComma": "es5"
}
]
}
}
You can also put your Prettier config into a .prettierrc file, see an example above.
And finally run:
npm run lint:js
You can set up your editor to run eslint --fix
on save and it will reformat your code every time you save a file.
If you have ESLint in your editor, you may notice that it reports too many issues while you’re writing code because of Prettier. To solve this issue you can disable prettier/prettier
rule in your editor’s ESLint settings.
Stylelint can format your CSS with --fix
switch, check the Linting chapter to know how to set it up.
Formatting tools complement linting well. They eliminate one source of confusion and make sure your code is formatted in a consistent way.
You’ll learn about typing in the next chapter.
See the Automation chapter to learn how to automate code formatting.
This book is available through Leanpub. By purchasing the book you support the development of further content.