Adding Prettier

We are going to add Prettier to our project by following these steps in Visual Studio Code:

  1. Make sure you are in the frontend directory and execute the following command to install Prettier:
> npm install prettier --save-dev
  1. Now, we want Prettier to take responsibility for the style rules of ESLint. Let's install some npm packages that will do this: 
> npm install eslint-config-prettier eslint-plugin-prettier --save-dev

eslint-config-prettier disables ESLint rules that conflict with Prettier. Here, eslint-plugin-prettier is an ESLint rule that formats code using Prettier.

  1. Now, let's tell ESLint to let Prettier take care of the code formatting by adding the following highlighted changes to .eslintrc.json:
{
"extends": ["react-app","prettier"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": "error"
}
}
  1. Now, let's specify the formatting rules we want in a .prettierrc file in the frontend folder. So, let's create this file with the following content:
{
"printWidth": 80,
"singleQuote": true,
"semi": true,
"tabWidth": 2,
"trailingComma": "all"
}

These rules will result in lines over 80 characters long being sensibly wrapped, double quotes being automatically converted into single quotes, semicolons being automatically added to the end of statements, indentations automatically being set to two spaces, and trailing commas being automatically added wherever possible to items such as arrays on multiple lines.

  1. Now, we can go to the Extensions area in Visual Studio Code (Ctrl + Shift + X) and type prettier into the search box in the top-left corner. The extension we are looking for is called Prettier – Code formatter and is published by Esben Petersen:

  1. Click on the Install button to install the extension.
  2. We can get Prettier to format our code when a file is saved in Visual Studio Code by adding the following highlighted line to the settings.json file in the .vscode folder:
{
"eslint.validate": [
"javascript",
"javascriptreact",
{ "language": "typescript", "autoFix": true },
{ "language": "typescriptreact", "autoFix": true }
],
"editor.formatOnSave": true
}

So, that's Prettier set up. Whenever we save a file in Visual Studio Code, it will be automatically formatted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.167.151