Before it’s time to say goodbye to 2018, the first working week of 2019 is over. The upgrade of React project, which was supposed to be completed at the end of 2018, was not started until now due to various reasons. Upgrading React from 15.4 to 16.7 was a bit of a bumble, but the biggest headache was the messy code. Because constraints like ESLint were not used early in the project, the result was a variety of code styles, with semicolons popping in and out, tabs and Spaces, 2 Spaces and 4 Spaces, etc.

To quickly resolve these code style differences, I chose ESLint and Prettier. The “save autofix” feature in the VS Code editor is a great way to beautify your Code.

ESLint

ESLint is an open source JavaScript code checking tool that allows you to find problems while developing. It also provides CLI commands to format code according to ESLint rules. So we can fix the code style automatically with the –fix command after we configure the rules.

eslint --fix *.js
Copy the code

Prettier

Prettier differs from ESLint, where the main purpose of Prettier is code inspection. Prettier makes code “Prettier.” Prettier isn’t limited to formatting JavaScript code. It also supports TypeScript, Flow, CSS, JSX, HTML, GraphQL, JSON, and more.

Prettier is also easy to use:

1, Install Prettier

npm install --global prettier
Copy the code

2. Configure Prettier

Support. Js |. Json. | yaml. | yml suffix, such as specific configuration information can refer to website

// prettier.config.js or .prettierrc.js
module.exports = {
  trailingComma: 'es5',
  singleQuote: true.printWidth: 200,
};

Copy the code

3. Format code

Prettier [opts] [filename…] To specify the folder or file to format. Please refer to the official website for specific parameters

prettier --write [filename ...]
Copy the code

To use it with ESLint, simply add Prettier as an ESLint rule using eslint-plugin-prettier.

npm install --save-dev eslint-plugin-prettier
Copy the code

. Eslintrc. Json:

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

VS Code configuration

First install the ESLint extension and then modify the user Settings preferences -> Settings

Key configurations are as follows:

"eslint.autoFixOnSave": true
Copy the code

conclusion

Although Prettier could be added to the ESLint rule. But using the two together can be a conflict. Because Prettier has far fewer configurable items than ESlint, when conflicts occur, ESLint-config-Prettier tends to be modified to avoid errors, which IS not what I want. In order to solve this conflict, my current approach is as follows:

1, Format the whole project using Prettier first

prettier --write [filename ...]
Copy the code

2, Use the –fix command from ESLint to fix the conflict where Prettier is used.

eslint --fix *.js
Copy the code

If you have any suggestions or better practices, please let me know in the comments.