Code Style https://omedia.dev/ en Getting started with Prettier — Modern JavaScript Tooling (Part 1) https://omedia.dev/blog/getting-started-prettier-modern-javascript-tooling-part-1 <span>Getting started with Prettier — Modern JavaScript Tooling (Part 1)</span> <span><span lang="" about="/user/5" typeof="schema:Person" property="schema:name" datatype="">Giorgi Kapanadze</span></span> <span>Mon, 07/27/2020 - 18:36</span> <div class="f-body om-text-content"> <p>JavaScript has grown into an enormous ecosystem for the past couple of years, which makes learning this language exciting and challenging at the same time. The vast array of available tools and frameworks might be a roadblock for some junior developers who just can’t figure out where to start and what to use.</p> <p>The general rule of thumb is to get the basics of the language first and move to nuts and bolts down the road. For sure, this is a valid approach. In my experience, though, some tools can be essential even for the absolute beginners, and knowing how to set up and use those can make the learning curve smoother.</p> <p>So in this series of posts, I’ll be covering a couple of must-have (or, must-take-a-look) tooling of the modern JS ecosystem, as well as tips on how to use and integrate them in our projects.</p> <hr /> <p>Before we begin, let’s set up our environment. We won’t need much for the tools discussed in this post — just <a href="https://nodejs.org/en/download/">get the latest Node.js</a> on your machine, if you don’t have it installed already. Node is compatible with all three operating systems, so you’re free to use your OS of choice for the development machine.</p> <h2>Coding style</h2> <p>Imagine that you’re working on a project with a couple of fellow developers. All those guys and gals will have their preferred coding styles — from indentation preferences to bracket placements, line wrapping, and commenting methods. The resulting code of a team without a strict coding style guidelines will be a mess to read and hard to follow through.</p> <p>This is why the coding style and standards have to be agreed upon at the start of the project and followed by all members without any exceptions. But we’re all humans and we have this beautiful (but sometimes — annoying) thing called <a href="https://en.wikipedia.org/wiki/Muscle_memory">muscle memory</a>. Muscle memory in our fingers helps us perform routine tasks without even thinking (like creating a code block for IF statement) but also prevents us from “switching” between those behaviors quickly. This is why it’s pretty hard to switch your coding mannerisms from project to project and it’s unreliable to hope that the coding styles will be followed by every team member all the time.</p> <p><a href="https://prettier.io/"><strong>Prettier</strong></a> solves this problem by automating the code formatting.</p> <p>Let’s create a new directory and initialize NPM in it. Open terminal, jump to the project folder and run <code>npm init -y</code> command. This will create the following <code>project.json</code> file for us:</p> <img alt="snippet" data-entity-type="file" data-entity-uuid="6ec4b20b-3872-46c6-b131-eee2e362bb5d" src="/sites/default/files/inline-images/01.png" class="align-center" width="1430" height="844" loading="lazy" /> <p>Now we can add <strong>Prettier</strong> to our project. Use this command to install it in our project:</p> <pre> <code class="language-bash">npm install --save-dev prettier</code></pre> <p>The<code> --save-dev</code><strong> </strong>flag tells NPM to install this package only for the development environment (we won’t need it elsewhere since the code will be formatted during the development.) After the command is finished, we’ll have the <code>node_modules</code> folder in our project directory and the <code>package.json</code> will be updated as well (you’ll see the <code>devDependencies</code> group since the Prettier was installed for the dev environment only):</p> <img alt="snippet" data-entity-type="file" data-entity-uuid="50cd15d4-069c-429b-bb18-6b8731b0ad42" src="/sites/default/files/inline-images/02.png" class="align-center" width="1430" height="558" loading="lazy" /> <p>Now let’s make some mess for the Prettier to do its job. Create a new <code>.js</code> file and type some code without any formatting consistencies. Something like this:</p> <img alt="snippet" data-entity-type="file" data-entity-uuid="ec98a95e-5fa9-48cb-8a69-3959c3056c04" src="/sites/default/files/inline-images/03.png" class="align-center" width="1946" height="802" loading="lazy" /> <p>This code has several formatting issues: for one, the strings are written with both types of quotes — single and double; the <code>function</code> block is indented with 4 spaces, while the if-statement block is using 2 spaces for the same job; some lines are too long; and so on.</p> <p>Let’s put Prettier to work. Create a new script called <code><strong>format</strong></code> that runs the Prettier<strong> </strong>for us. Our <code>package.json</code> should look like this:</p> <pre> <code class="language-json">{ "name": "modern-js", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "format": "prettier --write" }, "keywords": [], "license": "ISC", "devDependencies": { "prettier": "^1.19.1" } } </code></pre> <p>The scripts described in <code>package.json</code> lets us run complex commands from the <code>node_modules/.bin</code> directory in a shortcut-like manner. Let’s take a look inside this folder:</p> <img alt="snippet" data-entity-type="file" data-entity-uuid="bad0db59-5bbe-4cf0-8901-796779e6310a" src="/sites/default/files/inline-images/04.png" class="align-center" width="1946" height="401" loading="lazy" /> <p><code>prettier</code> is a regular executable JavaScript file. Scripts in <code>package.json</code> help us create a “shortcut” for a command like this:</p> <pre> <code class="language-bash">./node_modules/.bin/prettier --write src/index.js</code></pre> <p>To run the same command with NPM script, we can just run this command from our project root directory (the same directory that holds <code>package.json</code>):</p> <pre> <code class="language-bash">npm run format src/index.js</code></pre> <p>The last part of both commands — <code>src/index.js</code> — tells Prettier which file to format. After the command is finished, our messy file will look like this:</p> <img alt="snippet" data-entity-type="file" data-entity-uuid="f98ec105-5e22-47ab-86e9-79f2dee488a6" src="/sites/default/files/inline-images/05.png" class="align-center" width="1673" height="1073" loading="lazy" /> <p>I think we can agree that this code is, indeed, <em>prettier</em>. But most importantly, it’s easier to read or quickly scan to understand its structure. The code is more consistent, line indentations are the same, <code>if-else</code> blocks look much better and chained methods are broken into lines.</p> <p>But this style might not be the same as what your team has agreed on. For example, the team might consider 2-space indentation as their default, or to use single quotes for strings, instead of double ones. This is why Prettier rules are configurable and you can change the defaults with the <code>.prettierrc</code> file. Let’s create it in our project’s root directory and put this piece of JSON in it:</p> <pre> <code class="language-json">{ "tabWidth": 4, "semi": true, "singleQuote": true }</code></pre> <p>With this we’re letting Prettier know that we prefer 4 spaces for indentation (<code>tabWidth</code>); also that we want semicolons to be compulsory (<code>semi</code>) and to force single-quotes for writing string literals instead of double ones (<code>singleQuote</code>).</p> <p>After running the format script again, we’ll get the <code>src/index.js</code> file formatted with our configured rules:</p> <img alt="snippet" data-entity-type="file" data-entity-uuid="2c2fb21a-5735-4bf7-a72b-4a0f80f381e0" src="/sites/default/files/inline-images/06.png" class="align-center" width="1673" height="1073" loading="lazy" /> <p>The configuration options we used are just a small part of the set <a href="https://prettier.io/docs/en/options.html">prettier configuration options</a> you can use to match its behavior with your project style guidelines.</p> <p>Before we wrap up, let’s extend our <code>format</code> command a bit and make it more flexible to use. Most probably, we’ll be needing the formatting guidelines forced on all files in our project, not just on a single one. Instead of running the script on all files one by one, we can specify a file name pattern for Prettier that will pick up all <code>.js</code> files inside our <code>src/</code> directory and it’s child directories as well.</p> <p>Open the <code>package.json</code> file and add the following script to the <strong>scripts</strong> object:</p> <pre> <code class="language-json">"format:all": "prettier --write \"src/**/*.js\""</code></pre> <p>To see the new script in action, create some more <code>.js</code> files in the <code>src/</code> directory; or create some directories in <code>src/</code> and put the <code>.js</code> files inside those.</p> <p>Now, when you run <code>npm run format:all</code> all your <code>.js</code> files in <code>src/</code> directory will be (recursively) picked up by Prettier and re-formatted with rules specified in the <code>.prettierrc</code> configuration file.</p> <hr /> <p>In this small introduction to <strong>Prettier</strong> you’ve learned how to use it in terminal and with NPM scripts. It’s very easy to integrate this tool in your project workflow, configure it, and forget about code formatting altogether. You can never think about the formatting guidelines of a specific project, just focus on your code and Prettier will do the rest.</p> <p>Prettier can also be integrated into your favorite code editor (for example, see extensions for <a href="https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode">VS Code</a>, <a href="https://atom.io/packages/prettier-atom">Atom</a>, or <a href="https://github.com/jonlabelle/SublimeJsPrettier">Sublime</a> editors). With integration like this, the code formatting will be performed every time you save the file, which makes using this tool even more comfortable and seamless.</p> </div> <div> <div><a href="/topic/prettier" class="e-tag-logo-tag"> Prettier </a> </div> <div><a href="/topic/javascript" class="e-tag-logo-tag"> <img src="/sites/default/files/2021-02/javascript.svg" alt="JavaScript" loading="lazy" width="16" height="16" /> JavaScript </a> </div> <div><a href="/topic/tooling" class="e-tag-logo-tag"> Tooling </a> </div> <div><a href="/topic/code-style" class="e-tag-logo-tag"> Code Style </a> </div> </div> <div> <img src="/sites/default/files/styles/blog_full/public/2021-03/prettier.png?itok=-ymTm9HG" width="1360" height="714" alt="" loading="lazy" typeof="foaf:Image" /> </div> <div id="field-language-display"><div class="js-form-item form-item js-form-type-item form-item- js-form-item-"> <label>Language</label> English </div> </div> Mon, 27 Jul 2020 14:36:23 +0000 Giorgi Kapanadze 22 at https://omedia.dev