Code Formatter Saves you Time and Energy
Steps to setup prettier in vite+react+typescript codebase
Automated code formatting can save you a big time by enforcing consistent coding styles and standards. It helps to reduce the bugs surface, makes code easier to read and understand.
In Javascript and Typescript codebases, the most popular code formatter used is prettier. It is an opinionated code formatter that can format the code with the help of rules that we set or defaults are used.
These are the default value of rules when you configure prettier as a default formatter.
Setup Prettier in Vite+React+TypeScript Codebase
If you scaffolded your project using Vite official template react-ts or react-swc-ts, then you need to perform these additional steps to install and configure prettier.
Install these packages
yarn add -D prettier, eslint-config-prettier, eslint-plugin-prettier
PS: eslint-config-prettier - turns off all eslint rules that might conflict with prettier
Add the following entries in eslint configuration file, e.g. .eslintrc.js or .eslintrc.cjs
In plugin array, add “prettier” as a value
Add this entry in extends array, make sure its the last entry of array “plugin:prettier/recommended“
Your file after changes should look like that
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
'plugin:prettier/recommended' // last entry of array
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh', 'prettier'], // add prettier here
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
Configure prettier rules - there are multiple ways to define prettier configuration, but I personally prefer to create a .prettierrc file at the root of project
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"printWidth": 100,
"singleQuote": false
}
Now, you can format your document On Save or manually as per your code editor.
In VSCode, from settings change your default formatter to prettier. Now, you can press Option + Shift + F
to format manually or you can enable Format on Save option from settings
Thank your so much for reading this newsletter. If you find it helpful, do spread the word about it and share in your network 😊