Use ESLint and Prettier to format your code in TypeScript
I think ESLint
[1] is an essential thing when you try to create a project using JavaScript/TypeScript. That would be an excellent tool to parse the potential issues in your code.
Let’s check the philosophy of ESLint:
- Everything is pluggable:
- Rule API is used both by bundled and custom rules
- Formatter API is used both by bundled and custom formatters
- Additional rules and formatters can apply at runtime
- Rules and formatters don’t have to be bundled to combine
- Every rule:
- Is standalone
- Can be turned off or on (nothing can be deemed “too important to turn off”)
- Can be set to a warning or error individually
- Additionally:
- Rules are “agenda-free” - ESLint does not promote any particular coding style
- Any bundled rules are generalizable
- The project:
- Values documentation and clear communication
- Is as transparent as possible
- Believes in the importance of testing
Setup ESLint
First of all, let’s install the ESLint
first.
1 | npm install eslint --save-dev |
The first one is the ESLint library for JavaScript, and the rest of them are ESLint plugins for TypeScript. Next, you will need to create a .eslintrc.yaml
configuration file to set up the rules and related parser for your TypeScript project.
1 | env: |
Put this file in the project directory. Please note that we don’t add any rules. You can read more about the rules here. A better way is to enable the recommended set of rules that the plugin provides.
1 | env: |
It’s the primary setting of ESLint. If you want to get more detail, I will recommend reading the ESLint GitHub.
Setup Prettier
Install Prettier
1 | npm install prettier --save-dev |
Create a .prettierrc.yaml
and put into your project directory
1 | trailingComma: "es5" |
Integrate Prettier
with ESLint
, in the .eslintrc.yaml
1 | env: |
Then you’re all set.
Integrate with VS Code
So far, we just set up all rules and plugins for this TypeScript project. There’s one thing we can do in the IDE to make our life easier. Open VSCode settings,
1 | "editor.formatOnSave": true, |
This setting will automatically format your code when you save the changed in the file. That means we don’t wait to submit the PR to Github and then get the error.