When I’m starting a new project using React, I like to set up the environment correctly first. So, after running create react-app, I like to remove the stuff I won’t use, so my project folder looks like this:
Then I start adding what I’m gonna use. In this article I’ll show you how I add ESLint, Prettier and EditorConfig to my projects.
First of all, I like to open the project folder on VS Code and use the integrated terminal. Then I run:
$ yarn add eslint -D
It will add ESLint as a development dependency. You can see it under the devDependencies inside the package.json file. After that we must start ESLint:
$ yarn eslint --init
As ESLint is always installed by npm and not by Yarn, I also remove the package-lock.json that is generated and, inside the root of my project, I run:
It makes Yarn refresh the dependencies inside yarn.lock.
To add Prettier, I do:
$ yarn add prettier eslint-config-prettier eslint-plugin-prettier babel-eslint -D
Now it’s time to edit the .eslintrc.js file. I make it look like this:
Explaining the rules:
The first one makes Prettier point every rule that doesn’t match to our code as errors. The second allows HTML code inside .js files. It is necessary to do that because in Airbnb style guide HTML code is expected to be inside .jsx files only. The last one disable a rule that forces us to use export default in every file.
After configuring the .eslintrc.js file, I create a .prettierrc file as follows:
It forces the use of single quotes inside our code, aligning it to the Airbnb style guide.
Last of all, I create a .editorconfig file inside the root of our project. It makes easier for other developers to work on the same code without having to change their editor configurations. To create it, first install the extension EditorConfig for VS Code and then, in the root of the project, right-click and select Generate .editorconfig. My file looks like this:
Now that everything is set up, it is important that in your VS Code settings.json you add the following lines:
It will automatically fix ESLint’s warnings/errors when you save your file.
Now we’re good to go and ESLint and Prettier should be working fine, making our code easier to understand and fix.