Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Modern JavaScript Web Development Cookbook

You're reading from   Modern JavaScript Web Development Cookbook Easy solutions to common and everyday JavaScript development problems

Arrow left icon
Product type Paperback
Published in Dec 2018
Publisher Packt
ISBN-13 9781788992749
Length 642 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Federico Kereki Federico Kereki
Author Profile Icon Federico Kereki
Federico Kereki
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

Preface 1. Working with JavaScript Development Tools 2. Using Modern JavaScript Features FREE CHAPTER 3. Developing with Node 4. Implementing RESTful Services with Node 5. Testing and Debugging Your Server 6. Developing with React 7. Enhancing Your Application 8. Expanding Your Application 9. Debugging Your Application 10. Testing Your Application 11. Creating Mobile Apps with React Native 12. Testing and Debugging Your Mobile App 13. Creating a Desktop Application with Electron 14. Other Books You May Enjoy

Formatting your source code with Prettier

If you work in a project with several other developers, sooner or later arguments as to how code should be formatted are certain to pop up, and they can keep going for a long time! Deciding upon a single standard for your source code is really needed, but if formatting depends on each person, it's certain that you will end with even more "standards" than team members! Take a look at the following illustration. Something you don't want to have in a team is extra friction or aggravation, and style arguments can take forever:

You cannot afford to have more than one standard.
This XKCD comic is available online at https://xkcd.com/927/.

The problem is worsened by the fact that modern JS projects will not only include JS source code, but also possibly TypeScript or Flow (see the Adding Flow for data types checks section later), JSX (see Chapter 6, Developing with React), JSON, HTML, CSS or SCSS, and even more.

After having tried out many source code formatters, I finally decided to use Prettier for all purposes. Prettier is an opinionated code formatter, which supports all the languages that I listed previously, reformatting source code according to a set of rules, thus ensuring that all code conforms to an expected style.

If you want to read the original description for Prettier, see the blog post at https://jlongster.com/A-Prettier-Formatter, where the author describes the rationale for the project and gives some details on implementation and options.

What does it mean, that it is opinionated? Many (or most) code formatters provide a very big set of configuration options that you can twiddle in order to get the code to look as you wish. On the other hand, Prettier has its own set of rules, with little leeway for configuration, and thus cuts short all arguments. Moreover, you can get it to work seamlessly with VSC, meaning that whenever you save the code, it will get reformatted.

Let's see some examples of this opinionating. Working with arrow functions (which we shall see in more detail in the Defining functions section of Chapter 2, Using Modern JavaScript Features), if the function has a single parameter, enclosing it in parentheses is optional:

const plus1= (x)=> 1+x

However, Prettier decides that in this case the parentheses should not be included. Also, note that it added several spaces for clarity, as well as the (optional) missing semicolon:

const plus1 = x => 1 + x;

Similarly, if you use promises (we'll see them in the Doing async calls compactly section of Chapter 2, Using JavaScript Modern Features) you may write something such as the following:

fetch('http://some.url').then((response) => {
return response.json();
}).then((myJson) => {
console.log(myJson);
}).catch(e => { /* something wrong */ });

However, it will get reformatted to the more usual following code:

fetch("http://some.url")
.then(response => {
return response.json();
})
.then(myJson => {
console.log(myJson);
})
.catch(e => {
/* something wrong */
});

Note how each .then(...) was pushed to a separate line, according to the most common style for JS. The formatting rules that Prettier applies are derived from usual practice, and it wouldn't be possible to list them all here. But, what really matters is that by using this tool, you may be certain that your whole team will be working in the same fashion.

If your team grumbles about some rule or other, remind them of the saying there's a right way, a wrong way, and the Army way! After adopting Prettier, there will be no place for style discussions any more, and peace will eventually reign.

How to do it...

Installing Prettier is very simple: you should just add the VSC extension, which you can find by searching for Prettier Code Formatter; as a check, the latest version (as of December, 2018) is 1.16.0, and the author is Esben Petersen. The plugin itself can be found in the VSC marketplace, at https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode. You can also install it globally (as we saw in the Installing packages for different purposes section earlier in this chapter) to be able to use it in scripts or from the command line with npm or yarn. See https://prettier.io/docs/en/install.html, and I'd recommend doing that.

There is one change you will want to make in the VSC preferences. Go to File | Preferences | Settings, and add the following line to your user configuration, so every file will be formatted automatically whenever you save it:

"editor.formatOnSave": true,
.
.
.

If you'd rather only apply Prettier to JS, then you should use this instead:

"[javascript]": {
    "editor.formatOnSave": true
},
.
.
.

As we said, Prettier is pretty opinionated as to how code should look, and there are only a few options that you can change. The available options can be set in package.json (which makes it easier for all the team to share them) in a "prettier" key. Some of the possibilities (meaning the ones you might want to modify) are as follows:

Option
Default value
Meaning
arrowParens
false
For arrow functions with a single parameter, whether to enclose it in parentheses.
bracketSpacing
true
Include a space after the opening brace of an object, and before the closing brace.
jsxBracketSameLine
false
If true, the ending > for a multiline JSX element will be added at the end of the last line; if false, it will be on a separate line.
printWidth
80
Maximum line size.
semi
true
Add semicolons at the end of every line, even if not needed.
singleQuote
false
Use single quotes for strings.
tabWidth
2
Indentation size.
trailingComma
none
Specify whether to add trailing commas or not, wherever possible. Options are none (never add such commas), es5 (add them where ES5 allows, as in arrays or objects), or all (add them even to function arguments).
useTabs
false
Use tabs for indentation.

Personally, the only ones I use are tabWidth:4 and printWidth:75, but the latter is for the sake of the book only, not for other work. My package.json thus includes the following; I have it just before the dependencies key, but you can place it elsewhere:

"prettier": {
"tabWidth": 4,
"printWidth": 75
},
.
.
.

You can also use Prettier independently of VSC, and in that case the configuration options should go in a .prettierrc file. See https://prettier.io/docs/en/cli.html and https://prettier.io/docs/en/configuration.html for more on this.

Finally, if you want to avoid Prettier code formatting for some reason or another, you can do the following:

  • Avoid all formatting for a given file by adding its path and name to a .prettierignore text file at the project root
  • Avoid reformatting a single sentence by preceding it with a // prettier-ignore comment

For the latter option, remember to use the appropriate comment style depending on the source code language. For example, in an HTML file's you would use <!-- prettier-ignore -->, while in CSS, it should be /* prettier-ignore */, and for JSX, {/* prettier-ignore */}.

How it works...

There are two ways of using Prettier. The first is to configure VSC to automatically format the code whenever you save it; following the instructions we saw earlier when we installed VSC, change the editor Format on save option to true, and you'll be set. Of course, you can also format the code whenever you want by right clicking and selecting the Format Document option.

You can also use Prettier online. Go to https://prettier.io/playground/, paste your code into the left panel, and you'll instantly get a formatted version in the right panel. Take a look at the following screenshot for an example of code reformatting:

Prettier online can be used to experiment with configuration parameters, or for a quick code reformatting session

If you want to experiment with the few available options, click Show Options at the bottom-left corner, and you'll be able to configure Prettier, according to what we saw in the previous section, see the following screenshot:

If you want to dynamically experiment with (the few available) Prettier settings, you can do so in the online playground

When preparing the code for this book, I set the right margin at 75, because that's what will fit in a printed page. I also set indentation to 4 characters, because I find it clearer. Other than that, I left everything as the default; fewer style arguments to deal with this way!

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime