Automating code formatting with Prettier

ESLint can be used to improve any aspect of your code, including how it's formatted. The problem with using something like ESLint for this job is that it only tells you about the formatting issues that it finds. You still have to go fix them.

This is why the ESLint configuration from create-react-app doesn't specify any code formatting rules. This is where a tool like Prettier comes in. It's an opinionated code formatter for your JavaScript code. It understands JSX out of the box, so it's ideally suited to format your React components.

The create-react-app user guide has a whole section on setting up Git commit hooks that trigger Prettier to format any code before it's committed: https://github.com/facebookincubator/create-react-app#user-guide.

I won't repeat this guide here, but the basic idea is that having Git hooks in place that invoke Prettier on any JavaScript source that's committed will ensure that everything is formatted, well, pretty. The downside to only relying on Git commit hooks is that you as a developer don't necessarily see the formatted code as you're writing it.

In addition to setting up Prettier to format JavaScript source with every commit, adding a code editor plugin can vastly improve the development experience. Once again, you can install the appropriate Atom package (or something similar; Atom is popular so I'm using it as the example editor here):

Once you have the prettier-atom package installed, you can use Atom to format your React code. By default, this package uses the key binding Ctrl + Alt + F to invoke Prettier to format the current source file. Another option is to enable formatting on save:

Now, every time you save your JavaScript source, Prettier will format it. Let's test it out. First, open up App.js and completely trash the formatting so that it looks something like this:

Gross! Let's save the file and see what happens:

That's way better. Imagine if you had to manually fix that mess. Prettier keeps your code clear with hardly any thought on your part.

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

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