Typing out JavaScript code can help you catch bugs early, make your code clearer, and improve the quality of your code. However, there may be some problems when you use both a formatter (for pretty-printing) and a linter. The foiler can override style changes from the formatter. They go in different directions.

In order to use them smoothly, they need to stand on the same starting line. This article discusses how to use the most popular formatter Prettier alongside the most popular linterESLint. This article explains how to set them up and use them both on the command line and in Visual Studio Code (VS Code) to automatically correct and format your Code.

There are many solutions to this problem, but some are hacker solutions. I will discuss the advantages and disadvantages of some of them. It’s up to you to decide which way to go.

First, let’s take a broad look at the hint rules so we can understand what the dividing line is between a hint and a formatter.

Polish rules

There are two main categories of hint rules.

  1. Formatting rules. These rules affect the style of the code. There are no bugs involved in these rules. For example, the ‘no-mixed-spaces-and-tabs’ rule in ESLint ensures that only tabs or Spaces are used for indentation. Prettier has a ‘tabs’ option for the same thing.
  2. Code quality rules. These rules can improve code quality and make it possible to prevent or catch errors. For example, the ‘no-implicit-globals’ rule in ESLint does not allow global-scoped variables. Global variables created from other scripts can have name conflicts. This often leads to runtime errors or unexpected behavior.

The problem is, Prettier and ESLint have overlapping rules, but we want them not to.

Generally speaking, we expect Prettier to handle the first category and ESLint to handle the second. There are some rules that might be hard to categorize as one of them. We don’t have to worry about which category they fall into. Our interest is in making sure Prettier or ESLint performs a specific action and doesn’t collide with each other.

As for the order in which Prettier is run, it is best to run Prettier before ESLint. Prettier formats a file by reprinting the entire program in a consistent way to eliminate any possibility of formatting errors. So if you want ESLint to take formatting action, you should run it after Prettier to prevent changes from being overwritten.

If you’re not familiar with ESLint and Prettier, I’ll show you how to initially configure them in the next section. If you are familiar with it, you can skip to the methods section.

Initial configuration of ESLint and Prettier

ESLint and Prettier can both be downloaded from NPM and Yarn. For each project, you create a package.json and add them as devDependencies.

npm install --save-dev eslint
npm install --save-dev --save-exact prettier

Copy the code

ESLint starts as a blank piece of paper. It doesn’t do anything until you create a configuration that contains some rules. Put your configuration files (.eslintrc.{js,yml,json}) in your project directory and you can lint. You can set a global configuration, but I discourage using ESLint, I still use a global configuration.

With configuration, you can run ESLint from the command line. You can read ESLint’s Getting Started Guide for more details.

Prettier, on the other hand, has a default configuration. It works without creating your own configuration file, so you can just start using it. It is advisable to use a specific version of Prettier on large projects, otherwise the update might cause many file changes and add noise to your Git commit. You should probably use a [. Prettierignore] (https://prettier.io/docs/en/ignore.html) file to ignore those things should not be formatted. You can read Prettier’s installation guide for more information.

A typical package.json would look like this. I target the files in the SRC and test folders for my NPM scripts. I like to skip the.eslintignore and.prettierignore files if possible – simpler ones are best!

{" name ":" basic - project ", "version" : "1.0.0", "main" : "index. Js", "scripts" : {" lint ":" NPX eslint SRC test ", "lint: fix" : "npm run lint -- -- -- fix", "prettier": "npx prettier src test --check", "prettier:fix": "NPM run prettier -- -- write" }, "author": "Rob O 'Leary ", "license": "ISC". "DevDependencies" : {" eslint ":" ^ 7.25.0 ", "prettier" : "^ 2.2.1"}}Copy the code

All major code editors have extensions for ESLint and Prettier. For VS Code, the official extensions are Prettier-code Formatter and ESLint.

Provide various methods for prompting and pret-print your code

I recommend the first method below.

1. Delete the conflicting rules and run them continuously

In ESLint, it is easy to turn off a rule that conflicts with Prettier by using the following configuration.

  • eslint-config-prettier for JavaScript
  • Tslint-config-prettier if you use TypeScript

First, install the configuration. This is just for JavaScript.

$ npm install --save-dev eslint-config-prettier

Copy the code

Then, in your local. Stylelintrc. * ESLint configuration file, the configuration name appended to [extends] (https://stylelint.io/user-guide/configuration/#extends) in the array. Be sure to put the prettier configuration last, so it overrides the Settings for the other configurations.

For example, eslintrc json:

{/ /... Extension. [/ /... 'eslint: it', "prettier" / / make sure this is the last], / /... }Copy the code

Now you can freely run Prettier and ESLint together without side effects.

You can run Prettier and ESLint one by one, as you would on the command line, by defining them as NPM scripts. Here’s what it looks like in package.json.

{" name ":" no worries - setup ", "version" : "1.0.0", "script" : {" lint ":" NPX eslint SRC test ", "lint: fix" : "npm run lint -- -- -- fix", "prettier": "npx prettier src test --check", "prettier:fix": "NPM run prettier -- -- write", "format":" NPM run Prettier :fix && NPM run lint:fix". } / /... }Copy the code

Configuration in VS code

  1. Install the extension. ESLint, Prettier, and Format Code Action.

  2. Update your user Settings (settings.json) as follows.

    {/ /... "editor.defaultFormatter": "esbenp.prettier-vscode", "eslint.probe": [ "javascript", "javascriptreact", "vue" ], "editor.formatOnSave": False, // Run Prettier, then run ESLint "editor.codeActionsOnSave": [ "source.formatDocument", "source.fixAll.eslint" ], "vetur.validation.template": false // ... }Copy the code

First, you need to disable the editor format (editor.formatonSave) when saving. We want to handle everything through code actions.

In March 2020 (v1.44), the editor.codeActionsOnSave property is updated to accept an array of code actions, which allows ordered code actions. If we install the Format Code Action extension, we can use formatting as a Code Action. So we can run Prettier and ESLint as code actions in any order we like.

In this example, we run Prettier with the source.formatDocument action (which uses the default format) and esLint –fix with the source.fixall.eslint action.

The slint.probe property is used to lock the language that ESLint should validate. If you want to see pop-up messages, you can use eslint.validate instead.

If you use the Vetur extension, make sure it doesn’t do its own validation. There is a set vetur. Validation. The template, you should not enable it.

2. Run Prettier and ESLint programmatically

The following application provides a uniform way to run Prettier and then immediately esLint –fix the file.

  • Prettier – eslint for JavaScript
  • prettier-tslint for TypeScript

First, install the package. This is just for JavaScript.

$ npm install --save-dev prettier-eslint

Copy the code

Next, you need to write your own implementation for your files and run the formatting.

Here is a basic example of formatting a string.

Const format = require("prettier-eslint") Const sourceCode = "const {foo} = bar"; Const options = {text: sourceCode, eslintConfig: {parserOptions: {ecmaVersion: 7,}, rule. { semi: ["error", "never"], }, }, prettierOptions: { bracketSpacing: true, }, fallbackPrettierOptions: { singleQuote: false, }, }; const formatted = format(options); // Notice that formatted text has no semicolons. // const { foo } = barCopy the code

Obviously, this method requires more work to lock the file, read the content, and write the output.

Configuration in VS code

You can install and use the Prettier ESLint extension, read the instructions in README.

3. Run Prettier as if it were an ESLint rule

This is usually not recommended because

  1. You will get a formatting problem reported by ESLint. Do you want Prettier to red line something you fix automatically?
  2. It’s slower than running Prettier directly.
  3. You have another layer on which to introduce errors.

You can use the ESLint plugin, which lets you run Prettier as a Linter rule.

  • Eslint – plugin – prettier for JavaScript
  • Tslint plugin – prettier is used in the TypeScript

First, install the plug-in. This is just for JavaScript.

$ npm install --save-dev eslint-plugin-prettier

Copy the code

Then, append the plug-in to the plugins array in your “.stylelintrc.*” file.

Example. Eslintrc. Json: * * * *

{" plugins ": [" prettier"]. "Rule ": {"prettier/prettier":" error "}}Copy the code

Weiss Booz recommended this approach a few years ago, and it was a reasonable choice at the time, but now there are more options.

Configure in VS code

  1. Install the extension. ESLint and Prettier.

  2. Update your user Settings (settings.json) as follows.

    "eslint.alwaysShowStatus": true, "editor.formatOnSave": "[javascript, javascriptreact]": {"editor.formatOnSave": {"editor. False}, // tell the ESLint plugin to run "editor.codeActionsOnSave": {"source.fixAll": True}, // Optional but important: if you enable the prettier extension for other languages such as CSS and HTML, turn off the JS extension because we already did that via ESLint. "prettier.disableLanguages": ["javascript", "javascriptreact"],Copy the code

conclusion

Prettier and ESLint can be used very effectively together. It requires some configuration, but after reading this article, it should be simple! It’s a great setup to take some tasks off your hands and regain some head space. It can help you improve the quality of your code and make your code base more readable without human intervention.

Original link; Blog.logrocket.com/automate-fo…