<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Prettier - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Prettier - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 21 May 2026 04:58:28 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/prettier/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Tutorial – How to Set Up a Front End Development Project ]]>
                </title>
                <description>
                    <![CDATA[ Let’s say you plan to build a website. Before you start, you want to set up a few tools to make your life easier. But which tools should you have? The JavaScript ecosystem is changing so fast that it can be overwhelming to pick the best tools to use.... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-set-up-a-front-end-development-project/</link>
                <guid isPermaLink="false">66c4c80d6e4b60b5b844529e</guid>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hunor Márton Borbély ]]>
                </dc:creator>
                <pubDate>Wed, 12 Feb 2025 21:44:03 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739318785959/23632d35-1d5a-4797-8c7d-fbad6c80a879.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Let’s say you plan to build a website. Before you start, you want to set up a few tools to make your life easier. But which tools should you have?</p>
<p>The JavaScript ecosystem is changing so fast that it can be overwhelming to pick the best tools to use. To solve this problem, in this article, I’m going to walk you through how to set up a front-end project from scratch.</p>
<p>We'll cover things like must-have editor extensions, adding JavaScript libraries to your project, why you'll use Node.js even if you want to do front-end development, and setting up an application bundler that will generate a live preview as you code in your browser.</p>
<p>You can also <a target="_blank" href="https://www.youtube.com/watch?v=BiBjuphZQxA">watch this article as a video</a> on YouTube. Let's dive in.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-how-to-choose-a-code-editor">How to Choose a Code Editor</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-auto-format-your-code-in-vs-code">How to Auto-format Your Code in VS Code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-do-you-need-node-for-a-front-end-project">Why Do You Need Node for a Front-End Project?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-run-your-project">How to Run Your Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-add-libraries-to-your-javascript-project">How to Add Libraries to Your JavaScript Project</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-get-coding-tips-while-you-code">How to Get Coding Tips While You Code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-initialize-a-project-with-vite">Initialize a Project with Vite</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ol>
<h2 id="heading-how-to-choose-a-code-editor"><strong>How to Choose a Code Editor</strong></h2>
<p>Let’s start with the foundations. As a web developer, you mostly edit text, so you need a good editor. So which one should you use?</p>
<p>Picking an editor is highly based on personal preference, as most editors have very similar features.</p>
<p>If you don’t have a personal preference, I highly recommend <a target="_blank" href="https://vscode.dev/">VS Code</a>. Lately, it has become the de facto standard editor for web development.</p>
<p><a target="_blank" href="https://survey.stackoverflow.co/2024/technology#1-integrated-development-environment"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738945424232/9f41d802-e672-4cd7-ada3-5e8d54000446.png" alt="VS Code is by far the most used editor" class="image--center mx-auto" width="3840" height="2160" loading="lazy"></a></p>
<p>One of the greatest features of all the mainstream editors is that you can add extensions to them. Let’s walk through two extensions that are must-haves.</p>
<h2 id="heading-how-to-auto-format-your-code-in-vs-code"><strong>How to Auto-format Your Code in VS Code</strong></h2>
<p>Prettier is an extension that makes your code more readable and more consistent.</p>
<p>Let’s say you copy-pasted some code, and it’s hard to read. The tabulation is off, a line is too long, and so on. Then you just save the file, and magically, everything looks as it should be.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738948709710/c64a427d-b868-4704-87db-338ebf079c67.png" alt="Prettier formats the code based on best practices" class="image--center mx-auto" width="2280" height="1280" loading="lazy"></p>
<p>This is what Prettier does. It formats the code based on best practices. It doesn't just fix tabulation and wrap the lines. It also adds parentheses to improve code readability, makes sure you are consistent with quotation marks, and many more.</p>
<p>To make it work in VS Code, we must first install the Prettier extension. To do so, go to the extensions panel in VS Code, search for Prettier, and then install it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738955063143/7e8378e5-cf70-4527-9951-b822a745f4bf.png" alt="To install Prettier, go to the Extensions panel, search for Prettier, and install it" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>Installing this extension doesn't format your files automatically on save by default. The default behavior is that once you install this extension, you can right-click within a file and select <strong>Format Document</strong>. You can also select part of a file and choose <strong>Format Selection</strong>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738955102891/2e55eaa7-ec2a-4aca-ad79-b1df82d31e5c.png" alt="Right-click within a file and select Format Document to format it" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>The first time you do this, you need to select the default formatter. VS Code already has a formatter, but it isn’t as powerful as Prettier. Now that you have two formatters, you have to let VS Code know that you want to use Prettier for formatting in the future.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738955119781/d0ef8bc3-54d0-4428-9731-c8857171f3e7.png" alt="The first time, you need to select the default formatter" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>If you wish to auto-format your files when you save them, you need to change the settings. Go to Settings in your VS Code preferences and search for the <strong>Format on Save</strong> option. By default, this is false, so make sure that you tick this checkbox. With this, Prettier formats your files every time you save them. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738955201893/fd3fbec6-5265-4c9b-adab-c1a9d524a635.png" alt="Set the Format On Save option in Settings" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>Formatting can be controversial, though. I highly recommend the default settings, especially for beginners. But if you prefer a different style, you can customize things.</p>
<p>You can indicate with comments to <a target="_blank" href="https://prettier.io/docs/en/ignore.html">ignore specific lines</a> and create a config file to list your preferences.</p>
<p>In the root folder of your project, you can create a file called <strong>.prettierrc</strong> and add a few options. A typical option could be if you prefer single quotes instead of double quotes in your files. Or if you don't want to have semi-colons at the end of your lines.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738955259640/d430386f-de2a-49f3-b252-aee4a9bc1089.png" alt="Adding a custom Prettier configuration" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>With this configuration, you will have a different format once you save your files.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"singleQuote"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">"semi"</span>: <span class="hljs-literal">false</span>
}
</code></pre>
<p>There are many more options, of course. If you want to dig deeper, check out <a target="_blank" href="https://prettier.io/docs/en/configuration.html">Prettier's documentation</a><a target="_blank" href="https://prettier.io/docs/en/configuration.html">.</a></p>
<h2 id="heading-why-do-you-need-node-for-a-front-end-project"><strong>Why Do You Need Node for a Front-End Project?</strong></h2>
<p>Before we get to the second must-have extension, we need to set up a few other things. First, we need to talk about Node.js. What is Node, and why do you need it even if you work as a front-end developer?</p>
<p>Node is often associated with backend development, but that's not its only job. Node is a JavaScript runtime – this means it runs JavaScript files outside of the browser.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949060189/11f39633-76a1-4c38-92ef-88846ffdeb8f.png" alt="You can run JavaScript as part of a website in your browser" class="image--center mx-auto" width="2200" height="1220" loading="lazy"></p>
<p>There are two ways of running JavaScript code. You can either have it as part of a website and run the entire website in a browser, or run only the Javascript file with a runtime like Node.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949071655/68552f47-63ba-4cfc-9ba0-abb9218a4857.png" alt="You can run JavaScript on its own with Node" class="image--center mx-auto" width="2200" height="1220" loading="lazy"></p>
<p>In the example below, we have a very simple Javascript file that prints "Hello World" to the console. If we have Node installed, we can go to the terminal, navigate to the folder where this file is, and then run it with Node like this. You can see that the file was executed, and the result is in the console.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738947073105/9b56af05-e925-4cd1-9475-b3e49898dd39.png" alt="Node can run JavaScript files on their own" class="image--center mx-auto" width="1280" height="720" loading="lazy"></p>
<p>That's what Node really is: a tool that runs JavaScript files on their own.</p>
<p>JavaScript mostly behaves the same way in both environments. But there are also differences in what JavaScript can do in a browser vs when it runs with Node.</p>
<p>For instance, when running in the browser, JavaScript can access and modify HTML elements. That's the main point of having JavaScript in the first place.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949133299/b1c6d0a6-ba11-4659-a51e-b72e4bbfde68.png" alt="In the browser, JavaScript can access and modify your HTML elements" class="image--center mx-auto" width="2200" height="1220" loading="lazy"></p>
<p>In Node, there's no HTML file. JavaScript runs on its own. On the other hand, in Node, JavaScript has access to your file system and can read and write your files.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949113586/e8702a9c-91bf-4096-8768-cf06e4e41082.png" alt="With Node, JavaScript can access and modify your File system" class="image--center mx-auto" width="2200" height="1220" loading="lazy"></p>
<p>For instance, you can run scripts on your machine to initialize a project. We are going to do that. You can run checks on your files and automatically correct the mistakes. Or you can run your test files.</p>
<p>In short, Node lets you run some tools that make your life much easier as a developer.</p>
<p>To install Node, go to <a target="_blank" href="http://nodejs.org">nodejs.org</a> and install it. If you are unsure if you already have Node, you can also go to your terminal and run <strong>node -v</strong> to check. If you get a version number, you have Node.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949153110/c9e63db3-d52b-4122-a31c-6b871ed2e4b5.png" alt="The website of Node.js" class="image--center mx-auto" width="2200" height="1220" loading="lazy"></p>
<p>So, why do people associate Node primarily with backend development? If the backend code is in JavaScript, the servers must run it somehow without a browser. So yes, if you are a backend developer using JavaScript, then you're most probably going to use Node. But Node is much more than that.</p>
<h2 id="heading-how-to-run-your-project"><strong>How to Run Your Project</strong></h2>
<p>Now that we have Node, we can use a live server to see our site live in the browser as we develop it. Without this, you need to manually refresh the browser window every time you make a change.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949223269/97bc1d15-4ab6-4204-88d6-257fa471f95d.png" alt="A bundler creates a package that you can run in the browser" class="image--center mx-auto" width="2248" height="1220" loading="lazy"></p>
<p>These tools are called bundlers because they take all your files and turn them into a neat package you can run in the browser. So why do you need them?</p>
<ul>
<li><p>They update your site live in the browser with hot reloading. When you save a file, you immediately see the result in your browser.</p>
</li>
<li><p>As web development tools have evolved, the browser won't understand your files when you use anything more advanced. For instance, are you using React? Then, you're using the JSX syntax – the one that looks like HTML. The JSX syntax is not part of JavaScript. You need a tool to convert it into plain JavaScript. Otherwise, it won't run in your browser. Or are you using TypeScript? You also need to turn that into JavaScript. Or, if you're using SCSS or any other CSS dialect, you need to convert it to plain CSS.</p>
</li>
<li><p>If you import libraries using the JavaScript module system, you need a live server to avoid CORS issues in your browser.</p>
</li>
</ul>
<p>This is what bundlers do. They make sure that you can use modern-day tooling while you're developing your application, and they can also create a final production build that you can publish on the internet.</p>
<p>How do you pick a bundler? There are several options, and essentially, they all do the same thing. The difference between them is in their performance, configuration options, and ease of use.</p>
<p>The most used bundler is still <a target="_blank" href="https://webpack.js.org/">webpack</a>, one of the earliest bundlers in the field. But the one that seems to have taken over the throne and gained more and more popularity is <a target="_blank" href="https://vite.dev/">Vite</a>. Here's a chart from the latest edition of the State of JavaScript survey.</p>
<p><a target="_blank" href="https://2024.stateofjs.com/en-US/libraries/#all_tools_experience"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738947476843/195adbd5-5aba-427e-9b00-c507542235d2.png" alt="The sentiment towards WebPack and Vite" class="image--center mx-auto" width="1540" height="900" loading="lazy"></a></p>
<p>This chart shows that while most developers have used Webpack, they don’t necessarily love it. At the same time, Vite's popularity is rising while still maintaining a positive sentiment.</p>
<p>If you haven't checked out the <a target="_blank" href="https://stateofjs.com/en-US">State of JavaScript</a> survey before, I highly recommend going through it. It gives you an excellent overview of the latest trends with JavaScript. You can learn which tools and libraries people love to use and which they will abandon soon. If you feel overwhelmed by all the changes in the JavaScript ecosystem, the results of this survey can be a great guide.</p>
<p>Once we have a folder for our project, let's navigate to it using our terminal. The easiest way to do this is to open the folder in VS Code and then use the built-in terminal. VS Code will open the terminal with the correct folder.</p>
<p>Then, you can run the project in the terminal with the following command. npx is a command line tool that comes with Node. This is one of the reasons we installed Node: to be able to run commands like this.</p>
<pre><code class="lang-bash">npx vite
</code></pre>
<p>The first time you run this script, it will ask you to install Vite. Say yes. Then, it will show you the URL of a local server, which you can open in a browser to view your project.</p>
<pre><code class="lang-bash">  VITE v6.1.0  ready <span class="hljs-keyword">in</span> 162 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h + enter to show <span class="hljs-built_in">help</span>
</code></pre>
<p>Now, if you update a file and save the changes, the new version appears in the browser immediately. It generates a live preview of your site until you stop the script or close the terminal. You can keep it running while you're developing your site.</p>
<p>Once you have finished, you can press <strong>Ctrl+C</strong> to stop the script. If it gets desynchronized or you break it with an error, restart it by pressing <strong>Ctrl+C</strong> to stop it and rerunning the same script. So that's how you run a project with Vite.</p>
<h2 id="heading-how-to-add-libraries-to-your-javascript-project"><strong>How to Add Libraries to Your JavaScript Project</strong></h2>
<p>Now that we have Node, we can also use npm or Note Package Manager to add libraries to our project. npm is another tool included with Node. So how does it work?</p>
<p>First, I will walk you through setting things up step by step the manual way so it's clear how the different parts come together. Then, I will show you how to automate most of these steps.</p>
<p>Navigate to your current folder in the terminal and run the following command to initialize the project. This command initializes a package.json file with some metadata.</p>
<pre><code class="lang-bash">npm init --yes
</code></pre>
<p>At this point, this file is not very interesting. It contains the project name, description, version number, and so on. You can change these values.</p>
<p>Now, we can add libraries to our package with the npm install command. In a <a target="_blank" href="https://www.freecodecamp.org/news/render-3d-objects-in-browser-drawing-a-box-with-threejs/">previous article</a>, we used Three.js to render 3D boxes in the browser.</p>
<p>So, as an example, let's install <a target="_blank" href="https://threejs.org/">Three.js</a>. Go to your terminal again, make sure you are in the correct folder, and run the following command:</p>
<pre><code class="lang-bash">npm install three
</code></pre>
<p>This command will install Three.js. But how do you know that the keyword is three here, not Three.js?</p>
<p>When you don’t know the package name, you can just google npm and the name of the library you need. Or, if you don't even know the library name, you can also just search for an npm 3D library and see what Google comes up with.</p>
<p>We can go through each package one by one and pick one based on their capabilities and other info. These packages mostly come with descriptions and quick examples to give you an idea of what the library can do for you.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738949563130/ce677d97-20c4-48ed-a168-b99eb01c84d4.png" alt="How to pick a library to use" class="image--center mx-auto" width="2260" height="1260" loading="lazy"></p>
<p>Another indicator you might want to look for is the weekly downloads and the date of the last update to ensure you select an actively maintained library that people still use.</p>
<p>Once you find the package you are looking for, you can see the command to install it at the top right corner: <code>npm i three</code>. The <code>i</code> here is just shorthand for install. Another way to learn how to install Three.js is to go to its official documentation and check the <a target="_blank" href="https://threejs.org/docs/index.html#manual/en/introduction/Installation">installation guide</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738952468171/7a54e0bb-d88d-428b-911c-cf7a71676562.png" alt="The package.json file after initializing the project and installing Three.js" class="image--center mx-auto" width="2260" height="1260" loading="lazy"></p>
<p>When we install a package, three things happen:</p>
<ul>
<li><p>It adds the latest version of Three.js in our package.json file as a project dependency.</p>
</li>
<li><p>It also creates a package-lock file, which NPM uses to keep track of the dependencies. You should never edit the dependency section of your package.json file or the package-lock file manually. Instead, you should always use commands like npm install and uninstall to add, remove, or update packages.</p>
</li>
<li><p>Finally, the node_modules folder gets created. This folder contains the source code of Three.js. When we import Three.js in our project, it looks for it in this folder. The content of this folder is also something that you should never change. You can look into it if you're interested in the source code of the library that you're using, but you shouldn't change it.</p>
</li>
</ul>
<p>If something goes wrong and you have an error with your dependencies that you can't figure out, then you can always safely delete the node_modules folder and the package-lock file and reinstall your dependencies based on the package.json file. This is not something that you should do, but you can always go back to having a clean slate.</p>
<p>Now that we have installed Three.js, we can create a simple website that displays a 3D box. It's a simple HTML file and a JavaScript file with the code for the 3D box. The key here is that we import Three.js with the import statement in the JavaScript file. This import will use the package that we just installed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738952825715/9828ea05-e75a-4fdf-b1a3-39bd3aa8e380.png" alt="Using Three.js in a sample project" class="image--center mx-auto" width="2546" height="1444" loading="lazy"></p>
<p>Then, we can run the project with Vite. Using imports means that we use the module system now. Running a project with the module syntax can be a bit tricky, as the browser gives you CORS errors by default. However, as we are using Vite to run our project, it works seamlessly without any questions. That’s one of the reasons we use Vite.</p>
<p>If you want to learn more about building 3D games with Three.js, check out my <a target="_blank" href="https://www.freecodecamp.org/news/three-js-tutorial/">earlier article</a> on building a minimalistic car in the browser.</p>
<h2 id="heading-how-to-get-coding-tips-while-you-code"><strong>How to Get Coding Tips While You Code</strong></h2>
<p>The second must-have editor extension is ESLint. While Prettier formatted the code, ESLint gives you coding tips.</p>
<p>It helps you catch basic mistakes and avoid patterns that can cause bugs or be misleading when you try to understand the code.</p>
<p>Here’s a simple example where you declare a variable, but then you have a typo, and you try to use another variable that doesn't exist. ESLint will highlight this for you. It will give you an error both at the variable declaration, saying that you created a variable you don't use, and add the usage, saying that you're trying to use a variable that is not declared. With ESLint, it's easy to spot that you made a typo.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738953388793/c081f406-f964-4c4c-95ef-83cdc8e403df.png" alt="c081f406-f964-4c4c-95ef-83cdc8e403df" class="image--center mx-auto" width="1928" height="1244" loading="lazy"></p>
<p>ESLint, of course, is much more complex than just being able to catch simple errors. There are also less obvious use cases where you might not understand why ESLint is complaining. Then, you can always click the link in the error popup for more details explaining why this pattern is harmful and what you can do to avoid it.</p>
<p>So how can we use ESLint in our projects? This time, we need to have an extension and a configuration. First, as we did with Prettier, we must install the ESLint extension. Go to your extensions, search for ESLint, and install it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738953594259/a6f02e96-069d-4463-8322-86a23c523df3.png" alt="To install ESLint go to the Extensions panel, search for ESLint, and install it" class="image--center mx-auto" width="2260" height="1280" loading="lazy"></p>
<p>We also need to set up ESLint for our project. Before we do that, we need to make sure that the project already has a package.json file. If you don't already have a package.json file, we first have to run <code>npm init --yes</code> to initialize the project. Then, we can generate an ESLint config with the following command:</p>
<pre><code class="lang-bash">npm init @eslint/config@latest
</code></pre>
<p>This script will ask you a few questions. Based on your answers, it will customize the configuration and the rules to check. For most cases, you can use the default option.</p>
<ul>
<li><p>The first time, it will ask for permission to install ESLint. Say yes.</p>
</li>
<li><p>Then, it will ask you whether to use ESLint only for syntax checks or to find problems as well. Choose the second option to get the most help from ESLint.</p>
</li>
<li><p>Then select that you’ll use it with JavaScript modules. Modern web development projects use the JavaScript module system. We use JavaScript modules if we have imports and exports in our code.</p>
</li>
<li><p>Then, it will ask what framework we are using. If we select a framework, it will add framework-specific rules to our project. For instance, using it with React will force us to define the prop types. If we don't use a front-end framework, just vanilla JavaScript, then select "None of these".</p>
</li>
<li><p>Then, it will ask if the project is using TypeScript. Choose based on your preference.</p>
</li>
<li><p>It asks where you run the code. As we have a front-end project, select "Browser".</p>
</li>
<li><p>Then, it will ask if you want to install the additional dependencies that are required for the rules based on your selections. Select yes.</p>
</li>
<li><p>It will also ask what package manager we’re using. We haven't talked a lot about this, but there are multiple package managers that we can use. Select the default: npm.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738953735596/a69f62ac-b5b4-459e-8e78-6956442adfe4.png" alt="Installing ESLint" class="image--center mx-auto" width="2640" height="1624" loading="lazy"></p>
<p>These were a lot of questions. Let's see what happened after we ran this command.</p>
<p>After this step, we have ESLint and some other dependencies based on the answers in the package.json file as development dependencies. Development dependency means that ESLint won't be part of your website's final code, but we need it during development.</p>
<p>ESLint also became part of our node_modules folder, and there are many more packages here now. This is because a dependency can have other dependencies, and the dependencies of the dependencies will also be part of the node_modules folder.</p>
<p>ESLint also created a config file that sets up the rules based on your answers. We will see how to customize the rules.</p>
<p>Now that ESLint is working, you should also see errors in the code once something is off. If you go to your JavaScript file and try to use an undeclared variable, ESLint will highlight the issue.</p>
<p>ESLint is also highly customizable. For instance, we might not want to mark an unused variable as an error. First, we go to the error popup and select the identifier of this type of error. Then, we go to the ESLint config and override this error as follows. Here, we can reduce the severity to a warning or completely turn off this rule.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738953834462/387e36f3-81ee-461c-ae02-3ca614c7b765.png" alt="Turning off ESLint rules in the config" class="image--center mx-auto" width="2640" height="1624" loading="lazy"></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> globals <span class="hljs-keyword">from</span> <span class="hljs-string">"globals"</span>;
<span class="hljs-keyword">import</span> pluginJs <span class="hljs-keyword">from</span> <span class="hljs-string">"@eslint/js"</span>;


<span class="hljs-comment">/** @type {import('eslint').Linter.Config[]} */</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> [
  {<span class="hljs-attr">languageOptions</span>: { <span class="hljs-attr">globals</span>: globals.browser }},
  pluginJs.configs.recommended,
  {
    <span class="hljs-attr">rules</span>: {
      <span class="hljs-string">"no-unused-vars"</span>: <span class="hljs-string">"off"</span>, <span class="hljs-comment">// Turn off the No Unused Variables rule</span>
    }
  }
];
</code></pre>
<p>But if you're a beginner, I recommend following the rules that ESLint has by default. Sometimes, it might be annoying to fix all the seemingly harmless issues, but all these rules are based on industry best practices, so it's good to follow them. For more details, check out <a target="_blank" href="https://eslint.org/docs/latest/use/configure/rules">ESLint's documentation</a>.</p>
<h2 id="heading-initialize-a-project-with-vite">Initialize a Project with Vite</h2>
<p>We walked through the step-by-step process of setting up a project. We used <strong>npm init</strong> to initialize the project, manually set up ESLint, and ran our project with Vite. Vite can also initialize the project with a sample application and all the necessary files, which is especially handy when we set up a React project. </p>
<p>Let's see how to set up a vanilla JavaScript and a React project. Let's navigate to a folder in the terminal that will contain our project. We don't need to create a project folder this time because the script will make it for us. Then, run the following command to initialize a project:</p>
<pre><code class="lang-bash">npm create vite@latest
</code></pre>
<p>This command asks you a few questions.</p>
<ul>
<li><p>First, it will ask you for the project name, which will also be the name of the folder created as the project root.</p>
</li>
<li><p>Then, it will ask what framework you use. If you don't use any framework and want plain old JavaScript, choose "Vanilla." If you use React, choose React.</p>
</li>
<li><p>Then, it will ask you if you want to use TypeScript or JavaScript. Here, the default is TypeScript. If you're a beginner in web development, choose JavaScript. If you are more confident with your skills, then go with TypeScript. TypeScript is more complicated, but it has become the industry standard in web development, and most jobs require you to know it. As a beginner, you can go with JavaScript.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738953943915/884e22b0-f096-4338-a392-588b032834f4.png" alt="Creating a project with Vite" class="image--center mx-auto" width="1364" height="966" loading="lazy"></p>
<p>Now, we can navigate to the new folder created and check out what we have here. If you choose a vanilla JavaScript project, you can see it generated a simple application with HTML, CSS, and some JavaScript files. You can change or even delete these. You'll need an HTML file as an entry point, but you can replace the rest.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738954107608/0234f409-6f78-4039-b5d1-133c8cd09530.png" alt="Vite can create a sample application with an HTML, CSS, and JavaScript file" class="image--center mx-auto" width="2624" height="1822" loading="lazy"></p>
<p>We can run this project with <strong>npx vite</strong> as we did before, but there’s a better way. For a real project, we want to add Vite as a development dependency to ensure consistency with the version we are using.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-project"</span>,
  <span class="hljs-attr">"private"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"0.0.0"</span>,
  <span class="hljs-attr">"type"</span>: <span class="hljs-string">"module"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"vite"</span>,
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"vite build"</span>,
    <span class="hljs-attr">"preview"</span>: <span class="hljs-string">"vite preview"</span>
  },
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"vite"</span>: <span class="hljs-string">"^6.1.0"</span>
  }
}
</code></pre>
<p>The package.json file shows that Vite has been added as a development dependency. To use this hardcoded version, we first have to install it via <code>npm install</code>. This command installs all the dependencies listed in the package.json file.</p>
<pre><code class="lang-bash">npm install
</code></pre>
<p>This package.json file now also has a scripts section. This section can define scripts to run your app locally, create a production build, or test your application. You can run them with <strong>npm run</strong>. So, for instance, to run the application, you can open the terminal with the correct folder and run the following command.</p>
<pre><code class="lang-bash">npm run dev
</code></pre>
<p>This runs the script labeled as “dev” in the scripts section, which will run the Vite version we just installed with <strong>npm install</strong>.</p>
<p>Vite does not install ESLint when you create a vanilla project, but you can always install it manually, as we did before with <strong>npm init @eslint/config@latest</strong>.</p>
<p>If you choose React as a framework when we initialize the project, we will have a couple more files. For instance, we have an ESLint config with the recommended React settings. We also have a Vite config that enables us to use React and a sample application that we can run.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1738954174340/26c5a9a5-b983-4ed7-8e43-fbab4400e08b.png" alt="Vite can also create a React project for you" class="image--center mx-auto" width="2624" height="1822" loading="lazy"></p>
<p>To run this app, we need to install the dependencies. So, let's go to the terminal and run <code>npm install</code>. This will install all the dependencies, including React. Then, we can run this app with <code>npm run dev</code>, and we will have a working React application.</p>
<h2 id="heading-summary">Summary</h2>
<p>In this article, we set up and run a front-end project with Vite. We also covered how to find and add dependencies, how to have consistent and automatic formatting with Prettier, and how to avoid bugs with ESLint.</p>
<p>What happens once you finish developing your app? How do you upload it to the web and share it with the world? That's the topic of a future article.</p>
<h3 id="heading-subscribe-for-more-tutorials-on-web-development"><strong>Subscribe for more tutorials on Web Development:</strong></h3>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/BiBjuphZQxA" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Set Up ESLint, Prettier, StyleLint, and lint-staged in Next.js ]]>
                </title>
                <description>
                    <![CDATA[ A linter is a tool that scans code for potential issues. This is invaluable with a programming language like JavaScript which is so loosely typed. Even for TypeScript, which is a strongly typed language whose compiler does a great job of detecting er... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-set-up-eslint-prettier-stylelint-and-lint-staged-in-nextjs/</link>
                <guid isPermaLink="false">66e88a49bd6e8dcd7dc5a8a2</guid>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Stylelint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Lint-Staged ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Naveed Ausaf ]]>
                </dc:creator>
                <pubDate>Mon, 16 Sep 2024 19:43:05 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1726515328917/f3ecbc80-6d06-45ee-b307-89ed1a7bc854.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A <strong>linter</strong> is a tool that scans code for potential issues. This is invaluable with a programming language like JavaScript which is so loosely typed.</p>
<p>Even for TypeScript, which is a strongly typed language whose compiler does a great job of detecting errors at compile time, linters such as ESLint have plugins that catch problems which are not caught by the compiler.</p>
<p>When you generate a new app using the Next.js CLI (<code>npx create-next-app</code>), ESLint is configured by default. But there are several problems with the linting setup generated by <code>create-next-app</code>:</p>
<ul>
<li><p>If you choose SCSS for styling, you should use <a target="_blank" href="https://stylelint.io/">Stylelint</a> in the build process to lint CSS or SCSS stylesheets. But it’s not set up automatically.</p>
</li>
<li><p>If instead you opt for Tailwind for styling, you should set up the Tailwind plugin for ESLint. But again, this isn’t done in the generated ESLint configuration.</p>
</li>
<li><p>If you choose TypeScript, then in Next.js v14 and below, TypeScript-specific ESLint rules are not configured, contrary to <a target="_blank" href="https://nextjs.org/docs/pages/building-your-application/configuring/eslint#typescript">what the documentation states</a>. While a Next.js v15 app has these set up, I would still tweak the setup further with the more powerful linting rules provided by the <a target="_blank" href="https://typescript-eslint.io/">typescript-eslint project</a>. These include the <a target="_blank" href="https://typescript-eslint.io/rules/no-floating-promises">no-floating-promises rule</a> which points out if you have forgotten to <code>await</code> a method that returns a <code>Promise</code>. These and other rules from typescript-eslint are going to save you lots and lots of times as you write TypeScript code.</p>
</li>
<li><p>And finally, Prettier is not set up. Prettier is a code formatting tool. It can prevent inconsistently formatted code from getting into the code repository, which would make comparisons between different versions of the same file difficult. Also, nicely formatted code is easier to work with. So this is a pretty big omission.</p>
</li>
</ul>
<p>In this tutorial, I'll show you how I set up linting and formatting in my Next.js projects in a way that addresses the issues above. I’ll also teach you how to install and configure some related VS Code extensions for coding assistance.</p>
<p>To follow along, you can either use a Next.js project you already have, or generate a new app by running <code>npx create-next-app</code> on the terminal.</p>
<p>If you’re scaffolding a new app, your choices are up to you (defaults are fine) but make sure to choose YES in response to the question about whether you’d like to use ESLint:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725930860799/fb38b3b2-5592-4eb4-b8d0-153aeb2d749d.png" alt="Terminal window in which Next.js scaffolder, create-next-app, is showing code generation options to the user" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>If you are following along with an existing app rather than a new one, upgrade it by running the <a target="_blank" href="https://nextjs.org/docs/pages/building-your-application/upgrading/version-14">following command</a> in app root:</p>
<pre><code class="lang-bash">npm i next@latest react@latest react-dom@latest eslint-config-next@latest
npm i --save-dev eslint
</code></pre>
<p>This will avoid versioning conflicts down the line.</p>
<p>If you cannot upgrade to the latest version, you’ll need to specify versions for packages that will be installed in this tutorial to get around any version conflicts. Be warned that this can be frustrating.</p>
<p>Now you’re ready to open up the app in your code editor and proceed as follows.</p>
<p><strong>MONOREPO NOTE:</strong> A monorepo is a Git repository that contains multiple projects, each in its own subfolder. For example <a target="_blank" href="https://github.com/naveedausaf/flowmazondotnet">this repo</a> is for a full-stack solution that contains two projects: a Next.js app in folder <code>flowmazonfrontend</code> and a .NET Core API project in folder <code>flowmazonbackend</code>:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743632328084/670c756d-a5f9-4333-80dc-446b3a5975bb.png" alt="Repo screenshot" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>If your Next.js app is contained in a monorepo that contains both a Next.js app and other projects, <strong>I</strong> recommend that you do all of the setup below within the Next.js app's folder. This is the folder you should open in your code editor and <code>cd</code> into on the terminal. There is one bit of setup (lint-staged and Husky) that will need to be done in the monorepo root folder. I shall point it out in due course.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>For this tutorial, I assume that you know how to:</p>
<ul>
<li><p>write a basic Next.js app with two or more pages.</p>
</li>
<li><p>install additional NPM packages into your app</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-introduction">Introduction</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-table-of-contents">Table of Contents</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-set-up-prettier">Set Up Prettier</a></p>
<ul>
<li><a class="post-section-overview" href="#heading-a-note-on-line-endings-in-prettier">A note on line endings in Prettier</a></li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-set-up-eslint">Set Up ESLint</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-basics-of-eslint-configuration">Basics of ESLint configuration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-eslint-setup-for-typescript">ESLint Setup for TypeScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-eslint-setup-for-tailwind">ESLint Setup for Tailwind</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-eslint-setup-for-prettier">ESLint Setup for Prettier</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-set-up-stylelint">Set Up Stylelint</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-set-up-packagejson-scripts">Set Up package.json Scripts</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-set-up-lint-staged">Set Up lint-staged</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-set-up-vs-code-extensions">Set UP VS Code Extensions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-final-checks-and-troubleshooting">Final Checks and Troubleshooting</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-set-up-prettier">Set Up Prettier</h2>
<p><a target="_blank" href="https://prettier.io/">Prettier</a> is an opinionated code formatter that can format pretty much any file (<code>.html</code>, <code>.json</code>, <code>.js</code>, <code>.ts</code>, <code>.css</code>, <code>.scss</code> and so on).</p>
<p>Set it up in yuor app as follows:</p>
<ol>
<li><p>Install Prettier:</p>
<pre><code class="lang-bash"> npm install --save-dev prettier
</code></pre>
</li>
<li><p>If you chose Tailwind for styling when generating the app, then install <code>prettier-plugin-tailwindcss</code>:</p>
<pre><code class="lang-bash">   npm install --save-dev prettier-plugin-tailwindcss
</code></pre>
<p> This package is a Prettier plugin and provides rules for reordering of Tailwind classes used in a <code>class</code> or <code>className</code> attribute according to a canonical ordering. It helps keep the ordering of Tailwind classes used in the markup consistent.</p>
<p> %[https://youtu.be/tQkBJXwzY8A?autoplay=1] </p>
</li>
<li><p>Create <code>.prettierrc.json</code> in youyr project root. If you’re using SCSS for styling, paste the following snippet into this file:</p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"singleQuote"</span>: <span class="hljs-literal">true</span>,
   <span class="hljs-attr">"jsxSingleQuote"</span>: <span class="hljs-literal">true</span>
 }
</code></pre>
<p> If you’re using Tailwind instead, paste the following into <code>.prettierrc.json</code>:</p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"plugins"</span>: [<span class="hljs-string">"prettier-plugin-tailwindcss"</span>],
   <span class="hljs-attr">"singleQuote"</span>: <span class="hljs-literal">true</span>,
   <span class="hljs-attr">"jsxSingleQuote"</span>: <span class="hljs-literal">true</span>
 }
</code></pre>
</li>
<li><p>Create <code>.prettierignore</code> file in the app root, with the following content:</p>
<pre><code class="lang-plaintext"> node_modules
 .next
 .husky
 coverage
 .prettierignore
 .stylelintignore
 .eslintignore
 stories
 storybook-static
 *.log
 playwright-report
 .nyc_output
 test-results
 junit.xml
 docs
</code></pre>
<p> This file ensure that files which are not app code (that is, those which are not <code>.js</code>, <code>.ts</code>, <code>.css</code> files and so on.) do not get formatted. Otherwise Prettier will end up spending too much time processing files whose formatting you don't really care about.</p>
<p> <code>'prettierignore</code> (the file we just created), <code>.eslintignore</code>, and <code>.stylelintignore</code> have been ignored because these are plain text files with no structure so Prettier would complain that it cannot format them.</p>
</li>
<li><p>Finally, <strong>I recommend</strong> that you follow the steps in <a target="_blank" href="https://nausaf.hashnode.dev/lf-vs-crlf-configure-git-and-vs-code-on-windows-to-use-unix-line-endings">this post</a> to set LF as the EOL character, both in the repo and in your VS Code settings. Reasoning for this is given in the following subsection.</p>
</li>
</ol>
<h3 id="heading-a-note-on-line-endings-in-prettier">A note on line endings in Prettier</h3>
<p>Prettier <a target="_blank" href="https://prettier.io/docs/en/options#end-of-line">defaults to LF (Line Feed character) for line endings</a>. This means that when it formats files, it will change all occurrences of the CRLF character sequence, if any, to LF.</p>
<p>LF is also the default in text editors and other tools in Unix-based systems (Linux, MacOS etc.). But on Windows, the default for line endings is CRLF (Carriage Return character, followed immediately by Line Feed character).</p>
<p>Windows tooling such as text and code editors can easily handle LF as line ending. But CRLF can be problematic for tools on Unix-based systems such as Linux and various flavours of Unix. Therefore it makes sense to only use LF as line endings in code as this would work on both Windows and Unix-based systems.</p>
<p>Configuring LF as the EOF character in Git repo and in code editors will bring your tooling in line with Prettier's default. It will also ensure that all files in the Git repo consistently have LF line endings. Thus if a contributor to your repo is on Windows which uses CRLF as EOL character, the code they add or modify in the repo would still use LF: the code editor would default new code files to LF; <code>git</code> commit` would convert any CRLFs to LF when committing.</p>
<p>Finally, setting LF as the line endings for the whole repo would avoid strange things that happen when on Windows, Prettier retains its default of LF but Git and your code editor continue to use their default of CRLF for line endings:</p>
<ul>
<li><p>When VS Code Prettier extension formats a file (for example, when the extension is set up to "autoformat on save"), it does not change CRLF line endings. But formatting the same file by running Prettier on the command line <strong>does change line endings to LF</strong>. This discrepancy can be annoying.</p>
</li>
<li><p>Git may show warnings like this when when you run <code>git add .</code>:</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725930986122/b5630966-e8dd-4f47-bb58-eed6eb023ea6.png" alt="Warnings shown by git add command when some of the files being added contain LF but the repo's line ending default is CRLF" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
</li>
</ul>
<h2 id="heading-set-up-eslint">Set Up ESLint</h2>
<h3 id="heading-basics-of-eslint-configuration">Basics of ESLint configuration</h3>
<p>ESLint comes with a number of linting rules out of the box. But you can also supplement these with ESLint plugins.</p>
<p>An <strong>ESLint plugin</strong> defines some linting rules. For example, if you look in the <a target="_blank" href="https://github.com/vercel/next.js/tree/canary/packages/eslint-plugin-next">GitHub repo for Next's ESLint plugin</a>, eslint-plugin-next, each file in the <a target="_blank" href="https://github.com/vercel/next.js/tree/canary/packages/eslint-plugin-next/src/rules"><code>src/rules</code></a> folder defines a linting rule as a TypeScript function. The <a target="_blank" href="https://github.com/vercel/next.js/blob/canary/packages/eslint-plugin-next/src/index.ts"><code>index.js</code></a> of the package then exports these rule functions in the <code>rules</code> object in its default export:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">module</span>.<span class="hljs-built_in">exports</span> = {
  rules: {
    <span class="hljs-string">'google-font-display'</span>: <span class="hljs-built_in">require</span>(<span class="hljs-string">'./rules/google-font-display'</span>),
    <span class="hljs-string">'google-font-preconnect'</span>: <span class="hljs-built_in">require</span>(<span class="hljs-string">'./rules/google-font-preconnect'</span>),
    <span class="hljs-string">'inline-script-id'</span>: <span class="hljs-built_in">require</span>(<span class="hljs-string">'./rules/inline-script-id'</span>),
    ...
</code></pre>
<p>The basic way to use these rules in your app is to install the plugin package, then reference it in the ESLint configuration file in the app's root folder.</p>
<p>For example, we can use rules from the <code>eslint-plugin-next</code> mentioned above by running <code>npm install --save-dev eslint-plugin-next</code>, then placing the following content in the ESLint config file <code>.eslintrc.json</code> in the app root:</p>
<pre><code class="lang-json">{
    plugins: [<span class="hljs-string">"next"</span>],
    <span class="hljs-attr">"rules"</span>: {
        <span class="hljs-attr">"google-font-display"</span>: <span class="hljs-string">"warning"</span>,
        <span class="hljs-attr">"google-font-preconnect"</span>: <span class="hljs-string">"warning"</span>,
        <span class="hljs-attr">"inline-script-id"</span>: <span class="hljs-string">"error"</span>,
    }
}
</code></pre>
<p>If you now run <code>npx eslint .</code> in your app's root folder, ESLint will lint every JavaScript file in the app against each of the three rules configured above.</p>
<p>There are three severities you can assign to a rule when configuring it for use: <code>off</code>, <code>warning</code> and <code>error</code>. As the snippet above shows, you enable a rule by assigning to it a severity of <code>warning</code> or <code>error</code> in the app's <code>.eslintrc.json</code>.</p>
<p>When referencing a plugin in your app's ESLint configuration file, the prefix <code>eslint-plugin-</code> in the plugin's package name is omitted. This is why the package that contains linting rules for Next.js, <code>eslint-plugin-next</code>, is referenced only as <code>"next"</code> in the snippet above.</p>
<p>Since it is quite cumbersome to configure a severity level - <code>off</code>, <code>warning</code> or <code>error</code> - for every single rule from every plugin that you want to use, the norm is to reference an <a target="_blank" href="https://eslint.org/docs/latest/extend/shareable-configs">ESLint sharable config</a> , or <strong>config</strong> for short, that is exported by an NPM package. This is a JavaScript object that declares plugins and configures rules from these with severity levels just as we did above.</p>
<p>For example, the default export from <code>eslint-plugin-next</code> also contains several ESLint configs. Here is a another snippet from <a target="_blank" href="https://github.com/vercel/next.js/blob/canary/packages/eslint-plugin-next/src/index.ts"><code>index.js</code> of the plugin</a>, this time showing exported ESLint configs in addition to the <code>rules</code> object for exporting rule functions:</p>
<pre><code class="lang-typescript"><span class="hljs-built_in">module</span>.<span class="hljs-built_in">exports</span> = {
  rules: {
    <span class="hljs-string">'google-font-display'</span>: <span class="hljs-built_in">require</span>(<span class="hljs-string">'./rules/google-font-display'</span>),
    <span class="hljs-string">'google-font-preconnect'</span>: <span class="hljs-built_in">require</span>(<span class="hljs-string">'./rules/google-font-preconnect'</span>),
    <span class="hljs-string">'inline-script-id'</span>: <span class="hljs-built_in">require</span>(<span class="hljs-string">'./rules/inline-script-id'</span>),
    ...
},    
configs: {
    recommended: {
      plugins: [<span class="hljs-string">'@next/next'</span>],
      rules: {
        <span class="hljs-comment">// warnings</span>
        <span class="hljs-string">'@next/next/google-font-display'</span>: <span class="hljs-string">'warn'</span>,
        <span class="hljs-string">'@next/next/google-font-preconnect'</span>: <span class="hljs-string">'warn'</span>,
        ...

        <span class="hljs-comment">// errors</span>
        <span class="hljs-string">'@next/next/inline-script-id'</span>: <span class="hljs-string">'error'</span>,
        <span class="hljs-string">'@next/next/no-assign-module-variable'</span>: <span class="hljs-string">'error'</span>
        ...

      }
    },
    <span class="hljs-string">'core-web-vitals'</span>: {
      plugins: [<span class="hljs-string">'@next/next'</span>],
      <span class="hljs-keyword">extends</span>: [<span class="hljs-string">'plugin:@next/next/recommended'</span>],
      rules: {
        <span class="hljs-string">'@next/next/no-html-link-for-pages'</span>: <span class="hljs-string">'error'</span>,
        <span class="hljs-string">'@next/next/no-sync-scripts'</span>: <span class="hljs-string">'error'</span>,
      },
    },
}
</code></pre>
<p>As you can see, in addition to the rules (there are many more than those shown above), the plugin also exports two configs - <code>recommended</code> and <code>core-web-vitals</code> - that enable different selections of the rules defined in the plugin by assigning severity levels of <code>error</code> or <code>warning</code> to them.</p>
<p>The config that is normally used in Next.js projects is <code>core-web-vitals</code>. We can use this config object in our app’s ESLint configuration file (<code>.eslintrc.json</code> in app root) as follows:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"extends"</span>: [<span class="hljs-string">"plugin:next/core-web-vitals"</span>]
}
</code></pre>
<p>Thus is much simpler than declaring the plugin in <code>plugins</code> object and then assigning a severity level of <code>error</code> or <code>warning</code> to each rule from the plugin that we want to use.</p>
<p>Note the difference between <em>Configuration File</em> – this is  the ESLint configuration file named <code>.eslintrc.json</code> - and <em>Shareable Config</em> (or <em>config</em> for short) – this is an object that configures some rules from an ESLint plugin for use in a client project by assigning severities to selected rules.</p>
<p>Contents of the configuration file are themselves a config. But in configuration files, we do not typically import a plugin and configure all rules from it that we want to use. Instead we almost always import a well-known/trusted config object that is exported by an NPM package. Such a config object - one that is exported by an NPM package for use in ESLint configuration files (in other packages/apps) - is also known as a <a target="_blank" href="https://eslint.org/docs/latest/extend/shareable-configs">shareable config</a>.</p>
<p>Typically, plugins - these define ESLint rules as JavaScript/TypeScript functions - also bundle their rules into one or more shareable configs. The <code>recommended</code> config from plugin <code>eslint-plugin-next</code> that we used above is just one such config.</p>
<p>Shareable configs do not only come from plugin packages, although it is customary for plugins to also export one or more shareable configs composed of their own rules. Other packages, whose names begin with <code>eslint-config-</code> (as opposed to <code>eslint-plugin-</code>) can provide one or more named configs.</p>
<p>Next.js provides one such package named <code>eslint-config-next</code>. This re-exports configs <code>recommended</code> and <code>core-web-vitals</code> from the plugin. It also re-exports (in v15 and above of the package) a config of TypeScript linting rules from plugin <code>typescript-eslint/eslint-plugin</code>. So instead of using <code>recommended</code> config from the plugin like we have done above:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"extends"</span>: [<span class="hljs-string">"plugin:next/core-web-vitals"</span>]
}
</code></pre>
<p>we could have installed the package <code>eslint-config-next</code> and used that in <code>.eslintrc.json</code>:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"extends"</span>: [<span class="hljs-string">"next/core-web-vitals"</span>]
}
</code></pre>
<p>Since the package's name is not prefixed with <code>plugin:</code>, ESLint considers it to be a config package, reconstructing the name as <code>eslint-config-next</code> rather than as <code>eslint-plugin-next</code>. Notice how with config packages also, we delete the canonical prefix <code>eslint-config-</code> when referencing it in the ESLint configuration file.</p>
<p><strong>NOTE:</strong> In order to reference a shareable config provided by a package that only provides such configs but does not define or export linting rules, such as <code>eslint-config-next</code>, all you need to do is install the package and add the shareable config to <code>"extends"</code> in your <code>.eslintrc.js</code>. This is shown in the snippet above.</p>
<p>But if you want to reference a shareable config from an ESLint <strong>plugin</strong>, for example the package <code>eslint-plugin-storybook</code> which exports a shareable config named <code>recommended</code>, but you do NOT want to configure individual rules exported by the plugin, then I am not sure whether you need to declare the package in <code>"plugins"</code> array in your <code>.eslintrc.js</code> or not. I would declare it in <code>"plugins"</code> anyway as it may actually be necessary but wouldn't do any harm if it's not. Almost every ESLint example that I have come across, such as <a target="_blank" href="https://typescript-eslint.io/getting-started/legacy-eslint-setup#step-2-configuration">this one</a><a target="_blank" href="https://typescript-eslint.io/getting-started/legacy-eslint-setup#step-2-configuration">, does t</a>he same. </p>
<p>For example, if I want to use shareable config <code>recommended</code> from plugin <code>eslint-plugin-storybook</code>, and even though I would not be configuring any individual linting rules provided by this plugin, I would both reference the config in <code>"extends"</code> and, just to be safe, declare the plugin itself in <code>"plugins"</code> (after installing the plugin via command <code>npm install -D eslint-plugin-storybook</code>):</p>
<pre><code class="lang-json">{
    <span class="hljs-attr">"plugins"</span>: [<span class="hljs-string">"storybook"</span>],
    <span class="hljs-attr">"extends: ["</span>plugin:storybook/recommended<span class="hljs-string">",]
}</span>
</code></pre>
<p>It is possible to reference multiple shareable configs in <code>extends</code>. In this case, all the rules from all configs are used - except where there are multiple configs that each provide a rule with the same name. In this case the last config, proceeding left to right, wins. This is to say where there is a naming conflict, ESLint will use the rule from the last config on the list.</p>
<p>It is possible to use <a target="_blank" href="https://eslint.org/docs/latest/use/configure/configuration-files-deprecated">ESLint configuration file formats other than JSON</a>. You can provid<a target="_blank" href="https://typescript-eslint.io/getting-started/legacy-eslint-setup#step-2-configuration">e the sa</a>me information as in an <code>.eslintrc.json</code> file in a JavaScript (<code>.eslintrc.js</code> or <code>.eslintrc.cjs</code>) or yaml (<code>.eslintrc.yml</code> or <code>.eslintrc.yaml</code>) file instead.</p>
<p>Also, ESLint has a new configuration file format often called <a target="_blank" href="https://eslint.org/docs/latest/use/configure/configuration-files">flat config</a> (which I haven't used here) where the config files are either JavaScript or TypeScript files.</p>
<p>Armed with an understanding of how to configure ESLint for use, you are ready to set up ESLint in your Next.js project. The sections below shows you how to do this.</p>
<h3 id="heading-eslint-setup-for-typescript">ESLint Setup for TypeScript</h3>
<p><strong>If your app uses TypeScript</strong>, modify the ESLint configuration file (.esilntrc.json) as follows:</p>
<ol>
<li><p>On the terminal, in app's root folder, run the following command:</p>
<pre><code class="lang-bash"> npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin typescript
</code></pre>
<p> <code>@typescript-eslint/eslint-plugin</code> provides a number of linting rules for TypeScript files, as well as shareable configs, that augment the checking that the TypeScript compiler does.</p>
<p> <code>@typescript-eslint/parser</code> is a parser that allows ESLint to parse TypeScript files (by default it can only parser JavaScript files).</p>
<p> I am adding TypeScript compiler as a package - <code>typescript</code> - because <a target="_blank" href="https://typescript-eslint.io/getting-started"><code>typescript-eslint</code> Getting Started instructions</a> do the same.</p>
</li>
<li><p>In app root folder, rename <code>.eslintrc.json</code> to <code>.eslintrc.js</code>. Then Replace contents of <code>.eslintrc.js</code> in app root with the following:</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">/* eslint-env node */</span>
 <span class="hljs-built_in">module</span>.exports = {
   <span class="hljs-attr">root</span>: <span class="hljs-literal">true</span>,
   <span class="hljs-attr">extends</span>: [
     <span class="hljs-string">'next/core-web-vitals'</span>,
   ],
   <span class="hljs-attr">plugins</span>: [<span class="hljs-string">'@typescript-eslint'</span>, <span class="hljs-string">'tailwindcss'</span>],
   <span class="hljs-attr">parser</span>: <span class="hljs-string">'@typescript-eslint/parser'</span>,
   <span class="hljs-attr">overrides</span>: [
     {
       <span class="hljs-attr">files</span>: [<span class="hljs-string">'*.ts'</span>, <span class="hljs-string">'*.tsx'</span>],
       <span class="hljs-attr">parserOptions</span>: {
         <span class="hljs-attr">project</span>: [<span class="hljs-string">'./tsconfig.json'</span>],
         <span class="hljs-attr">projectService</span>: <span class="hljs-literal">true</span>,
         <span class="hljs-attr">tsconfigRootDir</span>: __dirname,
       },
       <span class="hljs-attr">extends</span>: [
         <span class="hljs-string">'next/core-web-vitals'</span>,
         <span class="hljs-string">'plugin:@typescript-eslint/recommended'</span>,
         <span class="hljs-comment">//'plugin:@typescript-eslint/recommended-type-checked',</span>
         <span class="hljs-comment">// 'plugin:@typescript-eslint/strict-type-checked',</span>
         <span class="hljs-comment">// 'plugin:@typescript-eslint/stylistic-type-checked',</span>
       ]
     },
   ],
 };
</code></pre>
<p> <strong>This is what the various lines of this file do</strong>:</p>
<p> <code>/* eslint-env node */</code> stops ESLint from complaining that this is a CommonJS module. We have had to put this in because ESLint, as we have configured it here, does not allow CommonJS modules (which <code>.eslintrc.js</code> is, see <code>module.exports = ...</code> at the top) and expects modules in the project to be ES6.</p>
<p> <code>root: true</code> says this is the topmost ESLint configuration file even though there may be nested ESLint configs in subfolders.</p>
<p> <code>extends:</code> specifies various ESLint configs, each of which enables a collection of linting rules.</p>
<p> <code>'next/core-web-vitals'</code> is a config provided by <code>eslint-config-next</code> that bundles Next.js-specific rules (both for JavaScript and TypeScript, from an inspection of its code on GitHub).</p>
<p> The <code>recommended-type-checked</code> config (used in a nested <code>extends</code> within <code>overrides</code> object - this is explained shortly) is provided by <code>@typescript-eslint/eslint-plugin</code>. This plugin is part of the <a target="_blank" href="https://typescript-eslint.io/">typescript-eslint</a> project that publishes packages for linting rules and parsers to support linting of TypeScript files by ESLint.</p>
<p> The configs used is <a target="_blank" href="https://typescript-eslint.io/users/configs#recommended-configurations">described here</a>. It is a superset of the non-type checked versions of the config, <code>recommended</code>. It adds linting rules which use TypeScript's type checking API for additional type information. These rules are more powerful than those contained in the base, non-type-checked <code>recommended</code> config that only rely on the ESLint parser for TypeScript - package <code>@typescript-eslint/parser</code>.</p>
<p> You might prefer to use the <code>strict-type-checked</code> and <code>stylistic-type-checked</code> configs, also provided by <code>@typescript-eslint/eslint-plugin</code>. These are stricter than what I have used.</p>
<p> The least strict choice for TypeScript linting would probably be the <code>recommended</code> config. This is what is re-exported by <code>eslint-plugin-next</code> as config named <code>typescript</code> and is referenced in <a target="_blank" href="https://nextjs.org/docs/app/building-your-application/configuring/eslint#typescript">Next.js instructions for setting up ESLint with TypeScript</a> as <code>next/typescript</code> (at least as of the time of this writing, September 2024). I prefer the config I have used instead.</p>
<p> <code>parser: '@typescript-eslint/parser'</code> specifies the ESLint TypeScript parser to be used instead of the default Espree parser which cannot parser TypeScript files.</p>
<p> <code>parserOptions:</code> tells the parser where to find the <code>tsconfig.json</code> file. This information allows the rules in the type-checked config used above - <code>recommended-type-checked</code> - to use TypeScript type checking APIs.</p>
<p> If we were using non-type-checked rules contained in other configs exported by the plugin, such as the <code>recommended</code> config, we would not need to provide this information.</p>
<p> <code>plugins: ['@typescript-eslint']</code> : I don't know what the purpose of this line is. It shouldn't be necessary and I have tested that the given ESLint configuration works fine without it. But it doesn't do any harm and was contained in <a target="_blank" href="https://typescript-eslint.io/getting-started/typed-linting">an example</a> in the plugin's documentation from which I adapted the above config. So I have kept it.</p>
<p> The <code>overrides</code> section ensures that the TypeScript parser options that we’ve had to configure in order to support type-checked configs apply only to <code>.ts</code> and <code>.tsx</code> extensions (from <a target="_blank" href="https://stackoverflow.com/questions/58510287/parseroptions-project-has-been-set-for-typescript-eslint-parser">this excellent StackOverflow answer</a>). Otherwise, if <code>parser</code> and <code>parserOptions</code> objects had been at the top level, then running ESLint on the project would throw errors on <code>.js</code> files.</p>
<p> This is a problem as we have several <code>.js</code> config files including the <code>.eslintrc.js</code> itself, so there will be linting errors. We can avoid these errors by using the override.</p>
</li>
</ol>
<h3 id="heading-eslint-setup-for-tailwind">ESLint Setup for Tailwind</h3>
<p><strong>If your app uses Tailwind,</strong> modify the config as follows:</p>
<ol>
<li><p>On the terminal, in app's root folder, run <code>npm install --save-dev eslint-plugin-tailwindcss</code></p>
</li>
<li><p>In ESLint config, add <code>"plugin:tailwindcss/recommended"</code> to the END of <code>extends</code>:</p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"extends"</span>: [<span class="hljs-string">"next/core-web-vitals"</span>, ..., <span class="hljs-string">"plugin:tailwindcss/recommended"</span>],

 }
</code></pre>
</li>
<li><p>In the ESLint config, add <code>"tailwindcss"</code> to <code>plugins</code> and add a <code>rules</code> object as shown below:</p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"plugins"</span>: [..., <span class="hljs-string">"tailwindcss"</span>],
   <span class="hljs-attr">"rules"</span>: {
     <span class="hljs-attr">"tailwindcss/classnames-order"</span>: <span class="hljs-string">"off"</span>
   },          
 }
</code></pre>
</li>
<li><p><strong>If your app uses TYPESCRIPT,</strong> then also add <code>"plugin:tailwindcss/recommended"</code> to inner <code>extends</code> inside <code>overrides</code> and duplicate the <code>rules</code> object inside <code>overrides</code>:</p>
<pre><code class="lang-javascript">   {
     ...
     overrides: [
     {
        <span class="hljs-attr">extends</span>: [<span class="hljs-string">"next/core-web-vitals"</span>, ..., <span class="hljs-string">"plugin:tailwindcss/recommended"</span>],
        <span class="hljs-attr">rules</span>: {
          <span class="hljs-string">'tailwindcss/classnames-order'</span>: <span class="hljs-string">'off'</span>,
        },
     }
   }
</code></pre>
</li>
</ol>
<p>In the Tailwind setup steps above, we have installed the package for the ESLint plugin for Tailwind, <code>eslint-plugin-tailwindcss</code>, and used the config <code>recommended</code> provided by the plugin.</p>
<p><code>eslint-plugin-tailwind</code> provides some useful linting rules for Tailwind CSS classes used in HTML or JSX/TSX markup. The biggest one for me is that if a class used in code is not a Tailwind class, there would be a linting error. This makes sense as when I am using Tailwind, I only use Tailwind-generated classes and do not define my own CSS classes.</p>
<p>The plugin also has a rule that checks that the sequence of Tailwind class names used in the <code>class</code> or <code>className</code> attribute in markup follows a canonical ordering. But we installed <code>prettier-plugin-tailwindcss</code> in our Prettier configuration above which also reorders Tailwind class names. So we don’t need this rule in ESLint and it might conflict with what Prettier does in our workflow.</p>
<p>We’ll turn this rule off, which is named <code>tailwindcss/classnames-order</code>, in the configuration above by declaring the plugin in <code>plugins</code> object, then setting the rule to <code>off</code> in the <code>rules</code> object.</p>
<h3 id="heading-eslint-setup-for-prettier">ESLint Setup for Prettier</h3>
<ol>
<li><p>On the terminal run:</p>
<pre><code class="lang-bash"> npm install --save-dev eslint-config-prettier
</code></pre>
</li>
<li><p>In ESLint config, add <code>"prettier"</code> to the END of <code>extends</code>:</p>
<pre><code class="lang-javascript"> {
   <span class="hljs-string">"extends"</span>: [<span class="hljs-string">"next/core-web-vitals"</span>, ..., <span class="hljs-string">"prettier"</span>]          
 }
</code></pre>
</li>
<li><p><strong>If your app uses TypeScript</strong>, then also add <code>"plugin:tailwindcss/recommended"</code> to the inner <code>extends</code> inside <code>overrides</code> also:</p>
<pre><code class="lang-javascript">  {
    ...
    overrides: [
    {
       <span class="hljs-string">"extends"</span>: [<span class="hljs-string">"next/core-web-vitals"</span>, ..., <span class="hljs-string">"prettier"</span>],
    }
  }
</code></pre>
<p> In the Prettier setup steps above, the config referenced as <code>prettier</code> is the name of the NPM package <a target="_blank" href="https://www.npmjs.com/package/eslint-config-prettier">eslint-config-prettier</a> with <code>eslint-config-</code> deleted. The default export from the package is an entire ESLint config object and this is the config we want to use.</p>
<p> So in this case, we do not suffix the name <code>prettier</code> with <code>/&lt;name of config&gt;</code> as we have done when referencing the named config <code>core-web-vitals</code> from package <code>eslint-config-next</code> when we referenced is as <code>next/core-web-vitals</code> (see step 1 above).</p>
<p> This config switches off those rules in ESLint that conflict with the code formatting done by Prettier. This should be the last config in <code>extends</code>.</p>
</li>
<li><p>Create <code>.eslintignore</code> in the project root. It doesn't need to have any content for now, but will come in handy in the future if ever you need to add folders or files that should be ignored by ESLint (see the final section of this post for an example).</p>
</li>
</ol>
<h2 id="heading-set-up-stylelint">Set Up Stylelint</h2>
<p>Stylelint is a linter for CSS and SCSS stylesheets.</p>
<p><strong>If you are using SCSS and NOT Tailwind,</strong> then set up Stylelint by following the instructions below. This set up will work for both CSS and SCSS files:</p>
<ol>
<li><p>On the terminal in project root run this command:</p>
<pre><code class="lang-bash"> npm install --save-dev sass
</code></pre>
<p> Next.js has <a target="_blank" href="https://nextjs.org/docs/basic-features/built-in-css-support#sass-support">built-in SASS/SCSS support</a> (so the Webpack config knows how to handle <code>.scss</code> and <code>.sass</code> files). But you still need to install a version of the <code>sass</code> package yourself, which is what we did above.</p>
</li>
<li><p>Next, install packages for Stylelint and its rule configs:</p>
<pre><code class="lang-bash"> npm install --save-dev stylelint stylelint-config-standard-scss stylelint-config-prettier-scss
</code></pre>
<p> Of these three packages:</p>
<ul>
<li><p><a target="_blank" href="https://stylelint.io/"><code>stylelint</code></a> is the linter.</p>
</li>
<li><p><a target="_blank" href="https://github.com/stylelint-scss/stylelint-config-standard-scss"><code>stylelint-config-standard-scss</code></a> is a Stylelint config that provides linting rules. It uses the Stylelint plugin <a target="_blank" href="https://www.npmjs.com/package/stylelint-scss">stylelint-css</a> and extends configs <a target="_blank" href="https://github.com/stylelint/stylelint-config-standard">stylelint-config-standard</a> which defines rules for vanilla CSS, and <a target="_blank" href="https://github.com/stylelint-scss/stylelint-config-recommended-scss">stylelint-config-recommended-scss</a> which defines SCSS specific rules. As a result, extending from this one config is enough to get linting support for both CSS and SCSS files.</p>
</li>
<li><p><a target="_blank" href="https://www.npmjs.com/package/stylelint-config-prettier-scss"><code>stylelint-config-prettier-scss</code></a> extends <a target="_blank" href="https://www.npmjs.com/package/stylelint-config-prettier">stylelint-config-prettier</a> and turns off those Stylint rules that conflict with Prettier's code formatting. This should be declared last in <code>extends:</code> array in <code>.stylelintrc.json</code> (as shown below).</p>
</li>
</ul>
</li>
<li><p>Now, create <code>.stylelintrc.json</code> in project root with the following contents:</p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"extends"</span>: [
     <span class="hljs-string">"stylelint-config-standard-scss"</span>,
     <span class="hljs-string">"stylelint-config-prettier-scss"</span>
   ],
   <span class="hljs-attr">"rules"</span>: {
     <span class="hljs-attr">"selector-class-pattern"</span>: <span class="hljs-literal">null</span>
   }
 }
</code></pre>
<p> The <code>"extends"</code> section declares the two Stylelint configs whose NPM packages we installed in the previous step.</p>
<p> The <code>"rules"</code> section is used to configure stylints rules. Here you can turn on or off, or configure the behavior of, individual Stylelint rules.</p>
<p> You can turn off a rule by setting it to <code>null</code>, as I have done for <code>"selector-class-pattern"</code>. I turned it off because it insists on having CSS classes in the so called kebab case (for example, <code>.panel-quiz</code> instead of <code>.panelQuiz</code>). I find it inconvenient for various reasons so I turned it off.</p>
</li>
<li><p>Next, create <code>.stylelintignore</code> in the project root with the following contents:</p>
<pre><code class="lang-json"> styles/globals.css
 styles/Home.module.css
 coverage
</code></pre>
<p> I created this file so that the two stylesheets generated by the Next.js CLI which do not comply with the linting rules can get ignored (there might be a better way of doing this but this works for me). Also, files in <code>coverage</code> folder do not need to be linted and would likely throw up errors.</p>
</li>
</ol>
<h2 id="heading-set-up-packagejson-scripts">Set Up <code>package.json</code> Scripts</h2>
<ol>
<li><p>The most important script is <code>"build"</code>. The default command for this script, <code>next build</code>, runs ESLint but not Prettier or (if you are using SCSS) Stylelint. So modify it in <code>package.json</code> file as follows:</p>
<p> <strong>If your app uses Tailwind, then:</strong></p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"scripts"</span>: {
     <span class="hljs-attr">"build"</span>: <span class="hljs-string">"prettier --check . &amp;&amp; next build"</span>,
     ...
</code></pre>
<p> <strong>Otherwise, if your app uses SCSS, then:</strong></p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"scripts"</span>: {
     <span class="hljs-attr">"build"</span>: <span class="hljs-string">"prettier --check . &amp;&amp; stylelint --allow-empty-input \"**/*.{css,scss}\" &amp;&amp; next build"</span>,
     ...
</code></pre>
<p> With this tweak to the existing <code>build</code> script, we can run <code>npm run build</code> either locally or in a CI/CD pipeline and it will fail not only on ESLint failure (this was the case before) but also on Prettier formatting or Stylelint failure.</p>
<p> Indeed if you <a target="_blank" href="https://nextjs.org/learn/basics/deploying-nextjs-app/deploy">deploy your app to Vercel</a>, the default pipeline there also calls <code>npm run build</code>. So when I introduced an error in one of my stylesheets, then deployed to Vercel, I got the following Stylelint error during deployment:</p>
<p> <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/om6228598f4pvb2iuwj9.png" alt="Stylelint errors when build script is run to build the app in Vercel's deployment pipeline" width="600" height="400" loading="lazy"></p>
<p> Note that I used the <code>--check</code> flag with <code>prettier</code> in the script (that is, I used the command <code>prettier --check .</code>). This runs Prettier in check mode, so it only checks for correct formatting and does not change the formatting.</p>
<p> I did this because the <code>build</code> script is what Vercel's deployment pipeline calls by default to build the code, and I don't want formatting to change during a CI build (nor do I want to tinker with Vercel defaults unless I absolutely have to).</p>
<p> To run Prettier locally to actually format the codebase, I define a separate <code>build:local</code> script which is same as <code>build</code> but runs Prettier without the <code>--check</code> flag, as well as a separate <code>format</code> script just to format with Prettier (but not build). These are set up below.</p>
</li>
<li><p>Set up the <code>"format"</code> script in your <code>package.json</code>. This formats the codebase with Prettier and comes in handy every now and then:</p>
<pre><code class="lang-json"> {
   <span class="hljs-attr">"scripts"</span>: {
     ...
     <span class="hljs-attr">"format"</span>: <span class="hljs-string">"prettier --write ."</span>
</code></pre>
</li>
<li><p>I recommend setting up a <code>build:local</code> script as follows:</p>
<p> <strong>If your app uses Tailwind,</strong> then:</p>
<pre><code class="lang-json"> <span class="hljs-string">"build:local"</span>: <span class="hljs-string">"prettier --write . &amp;&amp; next build"</span>
</code></pre>
<p> <strong>Otherwise, if your app uses SCSS,</strong> then:</p>
<pre><code class="lang-json"> <span class="hljs-string">"build:local"</span>: <span class="hljs-string">"prettier --write . &amp;&amp; stylelint --allow-empty-input \"**/*.{css,scss}\" &amp;&amp; next build"</span>
</code></pre>
<p> Since we cannot format the code with Prettier prior to executing <code>next build</code> in the existing <code>build</code> script (for reasons described above), we can use this script locally to format code then lint and build in one go.</p>
</li>
</ol>
<h2 id="heading-set-up-lint-staged">Set Up lint-staged</h2>
<p><a target="_blank" href="https://github.com/okonet/lint-staged">lint-staged</a> is a package that you can use to run formatting and linting commands on staged files in a Git repo. Staged files are those that have been added to the Git index using <code>git add .</code>. These are the files that have changed since the last commit and will get committed when you next run <code>git commit</code>.</p>
<p><a target="_blank" href="https://github.com/typicode/husky">Husky</a> is the typical choice in Node.js packages for registering commands to run in Git hooks. For example, registering the command <code>npx lint-staged</code> with Husky to run in the Git pre-commit hook means lint-staged will run automatically whenever you execute <code>git commit</code>.</p>
<p>At that time, the formatter (Prettier) and linters (ESLint or Stylelint) that have been configured to run in the lint-staged configuration file will run on the staged files. If there are any errors during formatting checks or linting, the commit will fail.</p>
<p>Whenever <code>git commit</code> fails due to linting errors, we can fix those, then run <code>git add .</code> and <code>git commit</code> again. Thus code only ever gets into the repo after it has been consistently formatted and verified to be free of linting errors. This is particularly advantageous in a team setting.</p>
<p>I prefer to only run <code>prettier --check .</code> on staged files. In particular, I do not change formatting of staged files and do not lint during a commit, for the following reasons:</p>
<p><strong>Reason for not formatting code:</strong> I almost always build and test my code before committing. Any code formatting should have happened prior to or during this local build and test.</p>
<p>I find the idea that code going into my repo should change automatically just as it is being committed <em>after</em> I have ascertained that any code changes are good to go, a little bit unappealing.</p>
<p><strong>Reason for not linting code:</strong> With TypeScript code, the compiler can catch a huge number of issues in code. The additional linting rules provided by <code>eslint-typescript/eslint-plugin</code> <a target="_blank" href="https://typescript-eslint.io/troubleshooting/faqs/typescript#why-dont-i-see-typescript-errors-in-my-eslint-output">only supplement the checks made by the TypeScript compiler</a>. So if I am linting code in staged files at commit time, I should build as well (so that the TypeScript compiler runs).</p>
<p>But building can be very time consuming on a large codebase. Besides, I almost always build and test before committing. Doing so implicitly runs linting (<code>next build</code> runs ESLint and my build scripts in <code>package.json</code>, as set up above, run any other linting that is necessary e.g. StyleLint). So I don’t feel the need to repeat lint or build on staged files via lint-staged.</p>
<p>Any lint- or build errors that might occasionally slip through into the Git repo would be pointed out when my Continuous Delivery pipeline builds the codebase (let's say in GitHub Actions on in Vercel's build pipeline). I can fix them then, in the pull request, before merge to <code>main</code>.</p>
<p>So, my personal preference is only to check for formatting on staged files, and neither reformat nor lint the code. This prevents inconsistently formatted code from getting into the Git repo where inconsistent formatting would make comparisons between different versions of the same file difficult.</p>
<p><strong>So now, set up lint-staged and Husky as follows:</strong></p>
<p><strong>Note</strong>: These tools need to be set up in the root of the Git repo. If you have a monorepo that contains multiple projects, including the Next.js app in which you performed the setup above, then open the root folder of this monorepo in your code editor and also <code>cd</code> into it on the terminal. Otherwise stay in the folder of your Next.js app.</p>
<ol>
<li><p>If you have a monorepo and its root folder does NOT have a <code>package.json</code> file, initialize an NPM package in the root:</p>
<pre><code class="lang-bash"> npm init -y
</code></pre>
</li>
<li><p>Install the lint-staged package:</p>
<pre><code class="lang-bash"> npm install --save-dev lint-staged
</code></pre>
</li>
<li><p>Create a file named <code>lint-staged.config.js</code> with the following contents:</p>
<pre><code class="lang-javascript"> <span class="hljs-comment">/* eslint-env node */</span>
 <span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);
 <span class="hljs-keyword">const</span> formatCommand = <span class="hljs-string">'prettier . --check'</span>;

 <span class="hljs-built_in">module</span>.exports = {
   <span class="hljs-string">'*'</span>: formatCommand,
 };
</code></pre>
</li>
<li><p>If you are in a monorepo, the <code>lint-staged.config.js</code> created above needs needs to be tweaked because in this, Prettier would be invoked from multi-repo root but the files it needs to format, as well as its config file (<code>.prettierrc.json</code>) and its ignore file (<code>.prettierignore</code>), are all in the subfolder that contains the Next.js app. Do the following:</p>
<ul>
<li><p><code>npm install --save-dev prettier prettier-plugin-tailwindcss</code></p>
</li>
<li><p>Replace the contents of <code>lint-staged.config.js</code> with the following. Make sure to substitute <code>&lt;Next.js app subfolder&gt;</code> with the actual name of your Next.js app folder:</p>
<pre><code class="lang-bash">  /* eslint-env node */
  const path = require(<span class="hljs-string">"path"</span>);
  const formatCommand =
    <span class="hljs-string">"prettier --check --config ./&lt;Next.js app subfolder&gt;/.prettierrc.json --ignore-path ./&lt;Next.js app subfolder&gt;/.prettierignore"</span>;

  module.exports = {
    <span class="hljs-string">"./&lt;Next.js app subfolder&gt;/**/*"</span>: formatCommand,
  };
</code></pre>
</li>
</ul>
</li>
<li><p>Install the Husky NPM package.</p>
<pre><code class="lang-bash"> npm install --save-dev husky
</code></pre>
</li>
<li><p>Run the following on the terminal in app root to configure Husky to run <code>lint-staged</code> whenever <code>git commit</code> runs (in Git's pre-commit hook):</p>
<pre><code class="lang-bash"> npx husky init
 <span class="hljs-built_in">echo</span> <span class="hljs-string">"npx lint-staged"</span> &gt; .husky/pre-commit
</code></pre>
<p> You should now have a file <code>.husy/pre-commit</code> in your app's folder (or in your monorepo root folder, if you're  working in a monorepo) with only one line: <code>npx lint-staged</code>.</p>
</li>
</ol>
<h2 id="heading-set-up-vs-code-extensions">Set Up VS Code Extensions</h2>
<p>If you use VS Code as your code editor, you can install the following VS Code extensions to provide linting and formatting on file save and syntax highlight on linting errors:</p>
<ul>
<li><p><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint">ESLint extension</a></p>
</li>
<li><p><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode">Prettier extension</a></p>
</li>
<li><p><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=stylelint.vscode-stylelint">Stylelint extension</a> (if you're using SCSS and not Tailwind)</p>
</li>
<li><p><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss">TaliwindCSS extension</a> (if you are using Tailwind and not SCSS)</p>
</li>
</ul>
<p><strong>Put the following in a</strong> <code>settings.json</code> <strong>file in the</strong> <code>.vscode</code> <strong>folder in the project</strong> (you can of course put these settings in you User Preferences file also. You can access it from Command Palette <strong>Ctrl + P</strong>).</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"[javascript]"</span>: {
    <span class="hljs-attr">"editor.defaultFormatter"</span>: <span class="hljs-string">"esbenp.prettier-vscode"</span>
  },
  <span class="hljs-attr">"[typescript]"</span>: {
    <span class="hljs-attr">"editor.defaultFormatter"</span>: <span class="hljs-string">"esbenp.prettier-vscode"</span>
  },
  <span class="hljs-attr">"[typescriptreact]"</span>: {
    <span class="hljs-attr">"editor.defaultFormatter"</span>: <span class="hljs-string">"esbenp.prettier-vscode"</span>
  },
  <span class="hljs-attr">"[javascriptreact]"</span>: {
    <span class="hljs-attr">"editor.defaultFormatter"</span>: <span class="hljs-string">"esbenp.prettier-vscode"</span>
  },
  <span class="hljs-attr">"[scss]"</span>: {
    <span class="hljs-attr">"editor.defaultFormatter"</span>: <span class="hljs-string">"esbenp.prettier-vscode"</span>
  },
  <span class="hljs-attr">"stylelint.validate"</span>: [<span class="hljs-string">"css"</span>, <span class="hljs-string">"scss"</span>],
  <span class="hljs-attr">"editor.formatOnSave"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">"eslint.useFlatConfig"</span>: <span class="hljs-literal">false</span>
}
</code></pre>
<p>As they’re set up, the extensions will lint and format on Save.</p>
<p><code>"eslint.useFlatConfig": false</code> ensures that the ESLint extension is able to pick up your <code>.eslintrc.js</code> and doesn't look for <code>eslint.config.js</code> which is the filename for a config file in ESLint's new <a target="_blank" href="https://eslint.org/blog/2022/08/new-config-system-part-2/">flat config format</a> that I have NOT used in this post.</p>
<p>If you encounter any problems in getting the ESLint extension to work, turn on the extension's debug output by adding line <code>"eslint.debug": true</code> to the end of the <code>.vscode/settings.json</code> you just created. Then restart VS Code and look at ESLint extension's output in the OUTPUT window:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1746569174032/3e705307-1588-4dd2-bd28-98c2d118a07a.png" alt="3e705307-1588-4dd2-bd28-98c2d118a07a" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<h2 id="heading-final-checks-and-troubleshooting">Final Checks and Troubleshooting</h2>
<p>Now it’s time to build and commit:</p>
<pre><code class="lang-bash">npm run format
npm run build
git add .
git commit -m <span class="hljs-string">"fix: set up linting and formatting"</span>
</code></pre>
<p>Building and committing is a good sanity check for the setup we just did.</p>
<p>If anything had not been set up correctly, you might get errors either during build or at commit.</p>
<p>If you already had some code in the project, then there might be a few errors when you commit. Typically, these can be resolved by:</p>
<ul>
<li><p>Adding folders or files to one of the <code>*ignore</code> files. For example, I already had some code in my project with <a target="_blank" href="https://storybook.js.org/">Storybook</a> installed. So I had to add folders <code>.storybook</code> and <code>storybook-static</code> to each of <code>.stylelintignore</code>, <code>.eslintignore</code> and <code>.prettierignore</code> as all three tools complained about them.</p>
<pre><code class="lang-bash">  stories
  storybook-static
</code></pre>
</li>
<li><p>If Prettier complains (shows a <code>[warn]</code> or <code>[error]</code> on the terminal) about some files not being formatted properly, you either need to add them to <code>.prettierignore</code> or format them by running <code>npm run format</code> in the folder of your Next.js app.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743632684491/fa5f073f-4de4-4b55-be00-184f8a36c802.png" alt="fa5f073f-4de4-4b55-be00-184f8a36c802" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
</li>
<li><p>Adding plugins for specific file types. For example, I had Gherkin <code>.feature</code> files in my project to describe integration tests. Prettier couldn't format these. So I added the <a target="_blank" href="https://www.npmjs.com/package/prettier-plugin-gherkin?activeTab=readme">prettier-plugin-gherkin</a> by simply running:</p>
<pre><code class="lang-plaintext">  npm install  prettier-plugin-gherkin --save-dev
</code></pre>
<p>  Note that <a target="_blank" href="https://prettier.io/docs/en/plugins.html">usually it is enough to install the package for a Prettier plugin</a> for Prettier to locate it and additional configuration is not required.</p>
<p>  Likewise, ESLint complained when it encountered <code>.cy.ts</code> files containing Cypress interaction tests for my app. To resolve this linting error, I installed the NPM package for Cypress ESLint plugin and configured it <a target="_blank" href="https://github.com/cypress-io/eslint-plugin-cypress#installation">as described here</a> (unlike Prettier, to get this ESLint package to work, some configuration was required).</p>
</li>
<li><p>The typescript config might be too strict and there might be a lot of errors when you build, such as:</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1725931098287/9618aff2-844b-4b15-9b14-2c8d377bf8c8.png" alt="ESLint error that occur on build when an ESLint config for TypeScript is used that is too strict." width="600" height="400" loading="lazy"></p>
<p>  If you do not want to fix individual errors in your existing codebase, and they are too many to disable specific rules at error locations using ESLint comments (see below), then the simplest solution would be to disable the <code>@typescript-eslint/recommended-type-checked</code> config by commenting it out in <code>.eslintrc.js</code> and uncommenting <code>@typescript-eslint/recommended</code> which is less strict.</p>
</li>
<li><p>Sometimes it is safe to turn off a linting rule at a specific line or for a whole file. While I am always wary of doing this, in a (deliberately bad) experimental code file, I had many instances of an error that VS Code ESLint extension pointed. This was not caught before but was now being pointed out because strict TypeScript linting rules had been enabled:</p>
<p>  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sg2ne9v2w8dbquv9ytad.png" alt="Intellisense in VS Code showing an ESLint error on a lint of code in a file." width="600" height="400" loading="lazy"></p>
<p>  So I pressed <code>Ctrl + .</code> to Show Code Actions (I could instead have clicked the yellow lighbulb icon shown next to the issue), then selected “Disable <code>@typescript/no-non-null-assertion</code> for the entire file”.</p>
<p>  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pqume7pod3jzflvblrus.png" alt="VS Code shows helpful tooltips when you click the bulb icon in the gutter. One of these allows y uoto disable an ESLint rule that is causing an error on the currently selected line of code." width="600" height="400" loading="lazy"></p>
<p>  This placed the comment <code>/* eslint-disable @typescript-eslint/no-non-null-assertion */</code> on top of my file to disable all instances of that particular error within the file:</p>
<p>  <img src="https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1d2kml4o11xpqaenk93b.png" alt="Special &quot;eslint-disable&quot; comment on top of a code file that disable a specific ESLint rule through the file." width="600" height="400" loading="lazy"></p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>This tutorial showed you how to configure linting and formatting tools in your Next.js app. I hope that it also gave you the background necessary both to understand the configurations given, and to customize them as needed.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How To Use Prettier in Visual Studio Code ]]>
                </title>
                <description>
                    <![CDATA[ Nowadays, every tech company strives to build quality software fast. That's why every developer must learn how to write clean and readable code.  But when a project is managed by multiple developers, the focus shifts into consistency especially in te... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-prettier-in-visual-studio-code/</link>
                <guid isPermaLink="false">66bc4d219212975c61bba79c</guid>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Visual Studio Code ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Matéu.sh ]]>
                </dc:creator>
                <pubDate>Mon, 18 Mar 2024 12:35:12 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/Prettier.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Nowadays, every tech company strives to build quality software fast. That's why every developer must learn how to write clean and readable code. </p>
<p>But when a project is managed by multiple developers, the focus shifts into consistency especially in terms of written code. </p>
<p>Keeping a consistent code style and formatting across many team members and project is a challenging task. It's almost impossible to do it manually, but that's where Prettier comes into play.</p>
<p>In this guide, you will learn how to install Prettier in Visual Studio Code and how to use it to format code.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before you follow this guide, you will need to download and install <a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a>.</p>
<h2 id="heading-what-is-prettier">What is Prettier?</h2>
<p>Prettier is a powerful code formatter that automates this process from start to finish. It gives you confidence that your code adheres to defined coding standards without any manual actions (unless you want to have it manual).   </p>
<p>Prettier not only supports all JavaScript libraries and frameworks, such as Angular, React, Vue, and Svelte, but also works with TypeScript.</p>
<p>That's why it is used by many people in tech worldwide.</p>
<h2 id="heading-how-to-install-prettier-in-visual-studio-code">How To Install Prettier in Visual Studio Code</h2>
<p>To install Prettier in Visual Studio Code, you need to:</p>
<ol>
<li>Open the Extensions tab.</li>
<li>Type prettier in the search box.</li>
</ol>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Prettier---1--2-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visual Studio Code / Extensions</em></p>
<p>At the top of the list you will find the Prettier - Code formatter extension. You need to open it, and click the Install button:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Prettier---2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visual Studio Code / Extensions / Prettier - Code Formatter</em></p>
<p>After the successful installation you will see the text saying "This extension is enabled globally"<em>:</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Prettier---2--1-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visual Studio Code / Extensions / Prettier - Code Formatter (Installation completed)</em></p>
<h2 id="heading-how-to-activate-prettier-in-visual-studio-code">How To Activate Prettier in Visual Studio Code</h2>
<p>When your Prettier extension is installed, you need to configure Visual Studio Code to take advantage of it. You can do in the Settings tab. </p>
<p>Side node: to open the Settings tab, you can use <code>COMMAND + ,</code> on macOS or <code>CTRL + ,</code> on Windows and Linux:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Prettier---4.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visual Studio Code / Main view</em></p>
<p>At the top of the Settings tab you will find a search box. Now, you need to type formatter, and then Editor: Default Formatter will pop up on the settings list:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Prettier---5.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visual Studio Code / Settings</em></p>
<p>Now, open the dropdown and select Prettier - Code formatter from the list:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Prettier---6.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visual Studio Code / Settings / Default Formatter</em></p>
<p>Now, Prettier is your default code formatter, but you might want to enable Visual Studio Code to automatically format code when you save files. </p>
<p>If you want to, just tick the checkbox in the Format On Save section:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Prettier---7.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visual Studio Code / Settings / Format On Save</em></p>
<h2 id="heading-how-to-format-code-with-prettier-in-visual-studio-code">How To Format Code with Prettier in Visual Studio Code</h2>
<p>Let's take a look at one React component I created: </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Prettier---8--2-.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visual Studio Code / Unformatted React 18 Component</em></p>
<p>As you can see, this code is completely misaligned, it misses semicolons, and it is very difficult to read. The code could formatted in a better way, right? Here's where Prettier comes into play.  </p>
<p>To format code, we need to open the command palette – you can use <code>COMMAND + SHIFT + P</code> on macOS or <code>CTRL + SHIFT + P</code> on Windows and Linux. </p>
<p>Now, you need to find Format Document. Feel free to use the search box:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Prettier---9.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visual Studio Code / Format Document command</em></p>
<p>After running Format Document your code becomes neat and clean:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/03/Prettier---10.png" alt="Image" width="600" height="400" loading="lazy">
<em>Visual Studio Code / Formatted React 18 Component (with Prettier)</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Integrating Prettier into Visual Studio Code is a game-changer for developers striving to maintain a consistent and high-quality codebase. </p>
<p>By automating the formatting process, you are not only adhering to coding standards but are also reducing the struggle that comes with manual code formatting. That's why every developer should use Prettier to ensure consistency in their codebase. </p>
<p>I hope this article helped you a lot. It'd mean the world to me if you shared it on your social media.</p>
<p>If you have any questions you can reach me on <a target="_blank" href="https://twitter.com/msokola">Twitter</a>.</p>
<h2 id="heading-learn-react">Learn React</h2>
<p>Looking for a practical course to learn React? </p>
<p>🚀 <strong>Join my <a target="_blank" href="https://assets.mateu.sh/r/fcc-prettier-guide">React 18 Course on Udemy</a></strong>.</p>
<p>This course includes:</p>
<ul>
<li>🎥 5.5 hours on-demand video</li>
<li>📱 Access on mobile and TV</li>
<li>🗓️ Full lifetime access</li>
<li>🎓 Certificate of completion</li>
</ul>
<p>Click below to enroll.</p>
<p><a target="_blank" href="https://assets.mateu.sh/r/fcc-prettier-guide"><img src="https://assets.mateu.sh/assets/fcc-prettier-guide" alt="React 18 on Udemy" width="600" height="400" loading="lazy"></a><br><em>Click to get started</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Linters and Code Formatters in Your Projects ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article we're going to take a look at two very useful tools we can use to make our lives easier when writing code: linting tools and code formatters. We're going to talk about what these tools are, how they work, why are they use... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/using-prettier-and-jslint/</link>
                <guid isPermaLink="false">66d45f27052ad259f07e4ad8</guid>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Mon, 10 Apr 2023 22:02:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/04/alysa-bajenaru-88IV5AtWjB8-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article we're going to take a look at two very useful tools we can use to make our lives easier when writing code: linting tools and code formatters.</p>
<p>We're going to talk about what these tools are, how they work, why are they useful, and finally see how we can implement them in a basic React project.</p>
<p>Let's go!</p>
<h1 id="heading-table-of-contents">Table of Contents</h1>
<ul>
<li><p><a class="post-section-overview" href="#heading-about-linting-tools">About linting tools</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-linting-tools">What are Linting Tools?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-are-linting-tools-useful">Why are Linting Tools Useful?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-main-linting-tools-in-the-market">Main Linting Tools in the Market</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-about-code-formatters">About code formatters</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-code-formatters">What are Code Formatters?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-are-code-formatters-useful">Why are Code Formatters Useful?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-main-code-formatters-available">Main Code Formatters Available</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-implement-eslint-and-prettier">How to Implement ESLint and Prettier</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-install-eslint">How to Install ESLint</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-install-prettier">How to Install Prettier</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping up</a></p>
</li>
</ul>
<h1 id="heading-about-linting-tools">About Linting Tools</h1>
<p>In the world of web development, linting tools have become an essential part of the developer's toolkit.</p>
<p>Linting tools are used to analyze source code for potential errors or stylistic issues, making it easier to maintain code quality and consistency across a project.</p>
<h2 id="heading-what-are-linting-tools">What are Linting Tools?</h2>
<p>Linting tools are automated tools that analyze source code to detect potential errors, security vulnerabilities, or coding style issues.</p>
<p>They are designed to help developers catch mistakes before they become a problem, and to promote best practices in coding.</p>
<p>The term "lint" comes from the name of the first lint tool, which was developed in the early 1970s by a team of Bell Labs researchers led by Stephen C. Johnson.</p>
<p>The original lint tool was designed to analyze C source code for potential errors and stylistic issues.</p>
<p>Since then, linting tools have evolved to work with a variety of programming languages, including JavaScript, Python, and Ruby.</p>
<h2 id="heading-why-are-linting-tools-useful">Why are Linting Tools Useful?</h2>
<p>Linting tools are useful for a number of reasons. Firstly, they help you catch errors early in the development process, when they are easier and cheaper to fix.</p>
<p>Secondly, they can help promote coding standards and best practices within a development team, ensuring that code is consistent and maintainable.</p>
<p>Finally, they can help you identify potential security vulnerabilities in your code, reducing the risk of a breach.</p>
<h2 id="heading-main-linting-tools-in-the-market">Main Linting Tools in the Market</h2>
<p>There are several linting tools available in the market today. Here are some of the most popular ones:</p>
<ol>
<li><p><strong>ESLint:</strong> <a target="_blank" href="https://eslint.org/">ESLint</a> is a widely used and highly configurable linter for JavaScript and TypeScript. It can be extended using plugins and supports various rule sets, making it a flexible tool for enforcing coding standards and preventing errors.</p>
</li>
<li><p><strong>JSHint:</strong> <a target="_blank" href="https://jshint.com/">JSHint</a> is a popular linter that has been around since 2010. It offers a simple configuration and a wide range of built-in rules to help developers avoid common pitfalls and improve code quality.</p>
</li>
<li><p><strong>JSLint:</strong> <a target="_blank" href="https://www.jslint.com/">JSLint</a> was one of the first linters to be developed for JavaScript, and it still sees some use today. It is known for its strictness and for enforcing a particular style of code, which can be helpful for maintaining consistency across a team.</p>
</li>
<li><p><strong>StandardJS:</strong> <a target="_blank" href="https://standardjs.com/">StandardJS</a> is a popular linter that aims to provide a "batteries included" approach to JavaScript linting. It has a minimal configuration and includes a set of opinionated rules designed to promote clean, readable code.</p>
</li>
</ol>
<p>And we should also talk about <strong>Typescript</strong>. When using <a target="_blank" href="https://www.typescriptlang.org/">TypeScript</a>, the TypeScript compiler itself acts as a linter. It checks the syntax of TypeScript code and provides warnings and errors when there are issues. This built-in linter can catch common mistakes and issues such as misspelled variable names, invalid method calls, and syntax errors.</p>
<p>The TypeScript compiler can be run using the <code>tsc</code> command in a terminal. When the <code>--noEmit</code> flag is used, the TypeScript compiler will only perform a syntax check without compiling the code to JavaScript. This allows the compiler to act as a linter and provide feedback on code quality without actually generating any output.</p>
<p>You can also configure the TypeScript compiler using a <code>tsconfig.json</code> file to specify various options, including the strictness of the checking. This can help catch even more potential issues and ensure that the code follows best practice</p>
<p>If you're not familiar with TypeScript, I recommend you <a target="_blank" href="https://www.freecodecamp.org/news/an-introduction-to-typescript/">this article I wrote a while ago</a>.</p>
<h1 id="heading-about-code-formatters">About Code Formatters</h1>
<p>In modern web development, code formatters have become an essential tool for developers. These tools automate the process of code formatting, making it easier to write and read code.</p>
<h2 id="heading-what-are-code-formatters">What are Code Formatters?</h2>
<p>Code formatters are automated tools that help you format source code automatically. The main purpose of code formatters is to standardize the formatting of code across a project or team, making it easier to read and understand code.</p>
<p>With code formatters, developers no longer need to spend time formatting code manually, which can save a lot of time and effort.</p>
<p>Code formatting tools have been around for decades. One of the earliest tools was the "indent" program, which was used to format C code in the early 1970s. But these early tools were limited and didn't have the same level of functionality as modern code formatters.</p>
<p>In the early 2000s, tools like "astyle" and "uncrustify" were developed, which introduced more advanced formatting capabilities.</p>
<h2 id="heading-why-are-code-formatters-useful">Why are Code Formatters Useful?</h2>
<p>Code formatters are useful for a variety of reasons. First and foremost, they help to standardize code formatting, which makes it easier to read and understand code. This is particularly important when working on large projects with multiple developers, where everyone needs to be able to read and understand each other's code.</p>
<p>Code formatters also help to ensure that code is consistent across a project or team, which can help to prevent errors and improve code quality. They also make it easier to maintain code over time, as the code is formatted consistently and is easier to read and understand.</p>
<h2 id="heading-main-code-formatters-available">Main Code Formatters Available</h2>
<p>There are several code formatting tools available in the market today. Here are some of the most popular ones:</p>
<ol>
<li><p><strong>Prettier:</strong> <a target="_blank" href="https://prettier.io/">Prettier</a> is a popular code formatter for JavaScript, TypeScript, and CSS. It's highly configurable and can be used in a variety of different environments, including editors, build tools, and code quality checkers.</p>
</li>
<li><p><strong>ESLint:</strong> While primarily known as a linting tool, <a target="_blank" href="https://eslint.org/">ESLint</a> can also be used as a code formatter. It has a <code>--fix</code> flag that can automatically format your code based on rules you define.</p>
</li>
<li><p><strong>Beautify:</strong> Beautify is a code formatter for JavaScript, HTML, and CSS that can be used in a variety of editors and IDEs. It allows you to customize your formatting options and has support for a wide range of languages.</p>
</li>
</ol>
<h1 id="heading-how-to-implement-eslint-and-prettier">How to Implement ESLint and Prettier</h1>
<p>Cool, so now let's see a linter and code formatter in action! We're going to implement the two most popular tools (ESLint and Prettier) in a simple React project to get an idea of how these things work.</p>
<p>First let's create our project by running this in our command line: <code>npm create vite@latest linternsAndFormatters --template react</code></p>
<p>Then <code>cd</code> into your project and run <code>npm install</code> so our dependencies get installed.</p>
<p>Now that we have our project up and running, we'll start by installing <strong>ESLint.</strong></p>
<h2 id="heading-how-to-install-eslint">How to Install ESLint</h2>
<p>To install ESLint, we can just run <code>npm init @eslint/config</code> in our console. This will fire a series of prompts asking how we want to use ESLint in our project and building the corresponding config. Your console might end up looking something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-72.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Installing ESLint</em></p>
<p>After all this, we'll see a new file called <code>.eslintrc.cjs</code> in the root of our project. Here's where ESLint's config lives and where we can customize the linter to our preferences. The initial config given the options I selected is the following:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
    <span class="hljs-string">"env"</span>: {
        <span class="hljs-string">"browser"</span>: <span class="hljs-literal">true</span>,
        <span class="hljs-string">"es2021"</span>: <span class="hljs-literal">true</span>
    },
    <span class="hljs-string">"extends"</span>: [
        <span class="hljs-string">"eslint:recommended"</span>,
        <span class="hljs-string">"plugin:react/recommended"</span>
    ],
    <span class="hljs-string">"overrides"</span>: [
    ],
    <span class="hljs-string">"parserOptions"</span>: {
        <span class="hljs-string">"ecmaVersion"</span>: <span class="hljs-string">"latest"</span>,
        <span class="hljs-string">"sourceType"</span>: <span class="hljs-string">"module"</span>
    },
    <span class="hljs-string">"plugins"</span>: [
        <span class="hljs-string">"react"</span>
    ],
    <span class="hljs-string">"rules"</span>: {
    }
}
</code></pre>
<p>To see our linter in action, let's add the following script in our <code>package.json</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"lint"</span>: <span class="hljs-string">"eslint --fix . --ext .js,.jsx"</span>
</code></pre>
<p>This script executes the <code>eslint</code> command with the <code>--fix</code> option to automatically fix linting errors and warnings. The command is executed on all files with the <code>.js</code> or <code>.jsx</code> extension located in the root directory of the project, as specified by the <code>.</code> argument.</p>
<p>Now let's modify our <code>app.jsx</code> file to have the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{

  <span class="hljs-keyword">const</span> emptyVariable = <span class="hljs-string">''</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Vite + React<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>Then run <code>npm run lint</code> and voilà! Your linter is screaming with red highlighted text that you have an unused variable in your code! =D</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/image-73.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-install-prettier">How to Install Prettier</h2>
<p>Cool, now let's hop on to our code formatter.</p>
<p>We're going to install it by running <code>npm install --save-dev --save-exact prettier</code>.</p>
<p>Then we're going to create and empty config file by running <code>echo {}&gt; .prettierrc.json</code>.</p>
<p>Since we're here, add the following options to your newly created config file:</p>
<pre><code class="lang-javascript">{
  <span class="hljs-string">"singleQuote"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-string">"jsxSingleQuote"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-string">"semi"</span>: <span class="hljs-literal">false</span>
}
</code></pre>
<p>What this does is assure single quotes are used whenever possible and semicolons are nowhere to be found (because, god, who likes semicolons...).</p>
<p>As we did with our linter, let's add the following script in our <code>package.json</code> file:</p>
<pre><code class="lang-javascript">    <span class="hljs-string">"format"</span>: <span class="hljs-string">"prettier --write ."</span>
</code></pre>
<p>The script runs the Prettier code formatter on all the files in the project directory and its sub-directories. When run with the <code>--write</code> option, it modifies the files in place, changing them to conform to Prettier's rules for indentation, line length, and other formatting options. The <code>.</code> argument specifies that all files in the project directory and its sub directories should be formatted.</p>
<p>Lastly, let's "uglify" the first line of our <code>app.jsx</code> file like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
</code></pre>
<p>Run <code>npm run format</code> and you should see it corrected right in front of you:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
</code></pre>
<p>You can breath easy now, those ugly semicolons won't come back to haunt you. ;)</p>
<p>As we've seen, the set up of these two tools isn't that complex, and they truly help to make our everyday jobs easier. ESLint will help us catch bugs and unnecessary/redundant code, and Prettier will help us standardize code format all across our codebase.</p>
<p>Another tip is that if you have a CI/CD pipeline in place, it's a good idea to implement the linting and formatting scripts as part of your workflow. This will help you ensure that every deployment is both automatically linted and formatted.</p>
<p>If you're not familiar with CI/CD or setting up a pipeline, I recently wrote <a target="_blank" href="https://www.freecodecamp.org/news/what-is-ci-cd/">an article about that</a>. ;)</p>
<h1 id="heading-wrapping-up">Wrapping up</h1>
<p>Linters and code formatters are powerful tools that can greatly benefit web developers.</p>
<p>Linters help you catch potential bugs and issues before they become serious problems, and encourage you to write more maintainable and readable code.</p>
<p>Code formatters help you enforce a consistent code style and format, saving time and reducing the chances of human error.</p>
<p>By using these tools in your web development workflow, you can improve your productivity and the quality of your code.</p>
<p>As always, I hope you enjoyed the article and learned something new.</p>
<p>If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">Twitter</a>. See you in the next one!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/04/4M2n.gif" alt="Image" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Alternatives to Prettier – Popular Code Linting and Formatting Tools ]]>
                </title>
                <description>
                    <![CDATA[ Many programmers hate code formatting because it is tedious and time-consuming. You can spend hours making sure everything is perfect and well-indented.  This is why code formatters are so useful. A code formatter is a tool that formats code accordin... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/alternatives-to-prettier/</link>
                <guid isPermaLink="false">66d0395a386d35c4e3bb3c39</guid>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kamaldeen Lawal ]]>
                </dc:creator>
                <pubDate>Wed, 15 Mar 2023 17:43:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/03/Alternatives-to-Prettier.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Many programmers hate code formatting because it is tedious and time-consuming. You can spend hours making sure everything is perfect and well-indented. </p>
<p>This is why code formatters are so useful.</p>
<p>A code formatter is a tool that formats code according to certain standards. It makes it so you don't have to worry as much about code formatting. Instead, you can focus on writing good code. This save time and also reduces your stress.</p>
<p>In this guide, we will talk about the Prettier code formatter. We will also talk about alternatives to Prettier like JsFmt, StandardJS, EsLint + EditorConfig, and Beautifier. Hopefully you’ll take away something that you can use to improve your code formatting.</p>
<h2 id="heading-brief-overview-of-prettier">Brief Overview of Prettier</h2>
<p><a target="_blank" href="https://prettier.io/">Prettier</a> is a popular code formatter that can handle complex code structures and format your code in a readable way.</p>
<p>It operates on the principle of no configuration required and it's designed to produce readable, consistent code. </p>
<p>Prettier is an opinionated tool that encourages programmers to follow its formatting rules. It also parses the code and reprints it uniformly.</p>
<h2 id="heading-why-explore-alternatives-to-prettier">Why Explore Alternatives to Prettier?</h2>
<p>There are many advantages of using Prettier. But like every other tool, exploring alternatives is sometimes a good idea. Here are some of the reasons for exploring alternatives to Prettier:</p>
<ol>
<li><strong>Inflexible style guides</strong>: Prettier adopts a strict set of formatting rules, and does not allow for much customization. Some programmers want a tool with a lot of configurations available.</li>
<li><strong>Speed</strong>: Although Prettier is fast, you may need a tool that provides faster and better performance in large codebases or real-time formatting.</li>
<li><strong>Language support</strong>: Prettier may not support (or might offer inadequate support) for the language you use.</li>
<li><strong>More features</strong>: While Prettier is open source, you might prefer a paid code formatter that has more features and better integration with other tools.</li>
</ol>
<p>In the guide, we will talk about four alternatives to Prettier. They are:</p>
<ul>
<li>JsFmt</li>
<li>StandardJS</li>
<li>ESLint+EditorConfig</li>
<li>JS Beautifier</li>
</ul>
<h2 id="heading-jsfmt-overview">JsFmt Overview</h2>
<p><a target="_blank" href="https://rdio.github.io/jsfmt/">JsFmt</a> is a code formatter that uses esformatter as a formatting tool. It automatically reformats JavaScript code according to a set of predefined rules. It is available specifically to re-write, format, search, and validate JavaScript code.</p>
<p>To install JsFmt, run this command:</p>
<pre><code>npm install -g jsfmt
</code></pre><p>A .jsfmtrc file, which can either be a JSON or INI formatted file, can overwrite any of the esformatter formatting options.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"indent"</span>: <span class="hljs-number">4</span>,
  <span class="hljs-attr">"line_ending"</span>: <span class="hljs-string">"unix"</span>,
  <span class="hljs-attr">"quote"</span>: <span class="hljs-string">"single"</span>
}
</code></pre>
<p>In this example, we specified the spaces for indentation to be four, we chose line-ending to be unix, and we picked single as the quote style for strings.</p>
<p>You can use the jsfmt rewrite method to change values in your JavaScript code. Here's an example of how to do that:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> x = <span class="hljs-number">5</span>;
<span class="hljs-keyword">const</span> y = <span class="hljs-number">10</span>;
<span class="hljs-keyword">const</span> z = x + y;
<span class="hljs-built_in">console</span>.log(z);

<span class="hljs-comment">//  The output will change to the below code after writing:  npx jsfmt --rewrite '5 -&gt; 20' reduce.js</span>

<span class="hljs-keyword">const</span> x = <span class="hljs-number">20</span>;
<span class="hljs-keyword">const</span> y = <span class="hljs-number">10</span>;
<span class="hljs-keyword">const</span> z = x + y;
<span class="hljs-built_in">console</span>.log(z);
</code></pre>
<p>To learn more about JsFmt, you can read its documentation <a target="_blank" href="https://github.com/rdio/jsfmt">here</a>.</p>
<h3 id="heading-features-of-jsfmt">Features of JsFmt</h3>
<ol>
<li>Formating: JsFmt can format code according to a set of predefined rules.</li>
<li>Integrations: you can integrate JsFmt with popular code editors like Visual Studio Code, Sublime Text, and Atom, making it easy to format your code directly in your editor.</li>
<li>Command-line interface: JsFmt allows you to format your code as part of your build process or development workflow in the command line.</li>
</ol>
<h3 id="heading-jsfmt-formatting-rules">JsFmt Formatting Rules</h3>
<p>Some of the formatting rules adopted by JsFmt are as follows</p>
<ol>
<li>Set indent: With the <code>--indent</code> option, JsFmt indents your code with two spaces per level.</li>
<li>Quotes: In JsFmt, single quotes are the default for strings, but you can change this with the <code>--double-quote</code> option.</li>
<li>Wrapping: you can use <code>--linene-width</code> to change the default wrap lines setting in JsFmt.</li>
<li>Semicolons: JsFmt adds semicolons at the end of each statement by default. You can disable this using the <code>--no-semi</code> option.</li>
</ol>
<h3 id="heading-pros-of-jsfmt">Pros of JsFmt</h3>
<ol>
<li>Formatting, searching, and re-writing of JavaScript.</li>
<li>Customizable: JsFmt's flexibility makes it a popular choice for many development teams. It is a highly customizable tool that you can configure to match the specific requirements of a project.</li>
</ol>
<h3 id="heading-con-of-jsfmt">Con of JsFmt</h3>
<ol>
<li>Lack of flexibility: despite the fact that it's customizeable, certain parts of JsFmt may not always be configurable to match the needs of your project.</li>
</ol>
<h2 id="heading-standardjs-overview">StandardJS Overview</h2>
<p><a target="_blank" href="https://standardjs.com/">StandardJS</a> is an open-source, no configuration linter, formatter, and JavaScript style guide. It checks the code for probable errors with the linter. It also formats code automatically, and helps you write code that is easy to read and understand.</p>
<p>It is the most popular option, coming in at 27,905 stars on GitHub clean code linter. It is also a powerful tool for ensuring the quality and consistency of your JavaScript code.</p>
<p>You can either install it globally or locally on your machine. To install globally, use the first command, while the second command is for installing locally. Note that to install it, you must have Node and npm installed on your computer.</p>
<p>To install globally: <code>$ npm install standard --global</code></p>
<p>To install locally: <code>$ npm install standard --save-dev</code></p>
<p>Alternatively, you can add StandardJS to the package JSON.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-cool-package"</span>,
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"standard"</span>: <span class="hljs-string">"*"</span>
  },
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"standard &amp;&amp; node my-tests.js"</span>
  }
}
</code></pre>
<p>The styles are checked automatically when you run the command:</p>
<pre><code>npm test
</code></pre><p>To illustrate how it works, check the JavaScript code below:</p>
<pre><code class="lang-javascript!">let number = 10;
if (number == 10) {
  alert("yes");
} else {
  alert("no");
}

// The Output after running the npm test in the terminal

&gt; test
&gt; standard &amp;&amp; node my-tests.js

standard: Use JavaScript Standard Style (https://standardjs.com)
  C:\Users\hp\Desktop\pretier\Js\script.js:5:5: Parsing error: Unexpected token else (null)
</code></pre>
<p>StandardJS shows that the code has a parsing error.</p>
<p>To fix most issues, run the following code:</p>
<pre><code>standard --fix
</code></pre><h3 id="heading-features-of-standardjs">Features of StandardJS</h3>
<ol>
<li>Community: A community of contributors guides the development of StandardJS by providing bug fixes and new features.</li>
<li>Linting: StandardJS linting catches style issues and programmer errors early.</li>
<li>Automatic code formatting: StandardJS get rid of messy and inconsistent code.</li>
<li>Command line integration: It has a command-line interface for running linter checks and auto-formatting code.</li>
</ol>
<h3 id="heading-standardjs-formatting-rules">StandardJS Formatting Rules</h3>
<p>Some of the widely used StandardJS formatting rules are listed below:</p>
<ol>
<li>Indentation: StandardJS enforces a consistent indentation level of 2 spaces by default. To strictly implement this, you need to add the <code>--fix</code> option.</li>
<li>Line wrap: StandardJS doesn't enforce the rule of line length, but it recommends keeping lines shorter than 80 characters. Use <code>$ myfile.js | standard --stdin</code> to manually check the file length.</li>
<li>Semicolons: StandardJS recommends using semicolons for clarity and to avoid potential issues. But the tool doesn't enforce this. To enforce the use of semicolons, use this:</li>
</ol>
<pre><code class="lang-json">{
  <span class="hljs-attr">"extends"</span>: <span class="hljs-string">"standard"</span>
}
</code></pre>
<ol>
<li>Spaces around operators: StandardJS recommends using spaces around operators, such as + and -, but it doesn't enforce this rule.</li>
</ol>
<h3 id="heading-pros-of-standardjs">Pros of StandardJS</h3>
<ol>
<li>Zero configuration: No decisions to make. StandardJS is the easiest way to enforce code quality in your project.</li>
<li>Easy installation: StandardJS is easy to install, and you can use it with most editors and IDEs.</li>
<li>Enhances Productivity: StandardJS saves developers time and increases productivity by formatting code according to its rules.</li>
<li>Wide support: Most editors and IDEs support StandardJS using plugins and integrations.</li>
<li>Consistency: StandardJS promote consistency across projects by enforcing a strict set of coding rules.</li>
</ol>
<h3 id="heading-cons-of-standardjs">Cons of StandardJS</h3>
<ol>
<li>Opinionated: Some developers may find the tool too opinionated. If that's the case, you might prefer to use other linting tools that allow for more customization.</li>
<li>Limited flexibility: StandardJS enforces a strict set of rules and conventions, which some developers may feel restricted by and prefer a more customizable approach.</li>
</ol>
<h2 id="heading-eslint-editconfig-overview">ESLint + EditConfig Overview</h2>
<p><a target="_blank" href="https://eslint.org/">ESlint</a> provides configurable rules that you can tailor according to your specific project needs. It is one of the most popular JavaScript linter that analyzes programming errors, bugs, and suspicious constructs.</p>
<p>You can extend its functionality by adding plugins, which can provide custom parsers and extra rules.</p>
<p>You'll need Node installed on your before installing ESLint. To install it, use the command below:</p>
<pre><code>npm init @eslint/config
</code></pre><p>Alternatively, you can create this manually on your machine:</p>
<pre><code>npm install --save-dev eslint
</code></pre><p>For both installations, you need to have installed a package.json file. If not, run this command</p>
<pre><code>npx eslint --init
</code></pre><p>The command will ask a series of questions about your project, coding style, and preferences to generate your configuration file.</p>
<p>You can run ESLint on any of your directories or files with this command:</p>
<pre><code>npx eslint yourfile.js
</code></pre><p>Rules can be turned off and you can run the toolonly with basic syntax validation, as ESLint is configurable and flexible to your use case.</p>
<p>Once you have generated the configuration file, you can customize according to your needs. The configuration file is a JavaScript file that exports an object with the configuration settings.</p>
<p>For example, you can specify the rules you want, plugins to use, and environments for your code:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"rules"</span>: {
    <span class="hljs-attr">"semi"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-string">"always"</span>],
    <span class="hljs-attr">"quotes"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-string">"double"</span>],
    <span class="hljs-attr">"indent"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-number">4</span>]
  }
}
</code></pre>
<p>The semi, quotes, and indent are the names of the rules in ESLint, while the error level of the rule is the first value. There are only three outputs for the first values. They are:</p>
<ul>
<li>"off" or 0 - turn the rule off</li>
<li>"warn" or 1 - turn the rule on as a warning (doesn’t affect exit code)</li>
<li>"error" or 2 - turn the rule on as an error (exit code will be 1).</li>
</ul>
<pre><code class="lang-json">{
  <span class="hljs-attr">"env"</span>: {
    <span class="hljs-attr">"browser"</span>: <span class="hljs-literal">true</span>,
    <span class="hljs-attr">"es2021"</span>: <span class="hljs-literal">true</span>
  },
  <span class="hljs-attr">"extends"</span>: <span class="hljs-string">"eslint: recommended"</span>,
  <span class="hljs-attr">"overrides"</span>: [],
  <span class="hljs-attr">"parserOptions"</span>: {
    <span class="hljs-attr">"ecmaVersion"</span>: <span class="hljs-string">"latest"</span>
  },
  <span class="hljs-attr">"rules"</span>: {
    <span class="hljs-attr">"indent"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-number">4</span>],
    <span class="hljs-attr">"quotes"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-string">"single"</span>],
    <span class="hljs-attr">"semi"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-string">"never"</span>]
  }
}
</code></pre>
<p>In this example, you specify that your code should run in a browser environment. Enable ECMAScript 2018 syntax, and follow the ESLint rules. You've also enabled three specific rules: indent, quotes, and semi.</p>
<p>The indent rule determines that an alert error will be thrown if indentation is more than 4 spaces. Likewise if you use double-quotes instead of single, there will be an error. You also specified not to use semi-colons.</p>
<p>To fix most of the issues in ESLint, use this command:</p>
<pre><code>npx eslint yourfile.js --fix
</code></pre><p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-number">6</span>, <span class="hljs-number">78</span>, <span class="hljs-number">8</span>];
<span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">"shola"</span>, <span class="hljs-string">"kamal"</span>];
<span class="hljs-built_in">console</span>.log(peoples);

<span class="hljs-comment">// The output</span>

 error  <span class="hljs-string">'numbers'</span> is assigned a value but never used  no-unused-vars
   error  Extra semicolon                               semi

✖ <span class="hljs-number">2</span> problems (<span class="hljs-number">2</span> errors, <span class="hljs-number">0</span> warnings)
  <span class="hljs-number">1</span> error and <span class="hljs-number">0</span> warnings potentially fixable <span class="hljs-keyword">with</span> the <span class="hljs-string">`--fix`</span> option.
</code></pre>
<h3 id="heading-editorconfig-overview">EditorConfig Overview</h3>
<p><a target="_blank" href="https://editorconfig.org/#file-format-details">EditorConfig</a> is an open-source file format. It provides standard ways of defining and maintaining coding styles in a project.</p>
<p>It maintains consistent coding styles which is especially useful when you have many developers working on the same project across various editors and IDEs. The tool consists of a collection of text editor plugins that enable editors to read the file format and adhere to defined styles.</p>
<p>You'll need to create a file named .editorconfig in the directory. EditorConfig plugins will look for the file in the directory of the opened file and on every parent directory.</p>
<p>Files are read from top to bottom, and a search for .editorconfig files will stop if the root file path is reached.</p>
<p>Creating an EditorConfig file is straightforward. Open a new file, and save it with .editorconfig as shown below.</p>
<p><img src="https://i.imgur.com/SHEafBl.png" alt="editorconfig file" width="237" height="34" loading="lazy"></p>
<p>Inside the .editorconfig file, the following wildcard patterns are used:</p>
<pre><code class="lang-javascript">root = <span class="hljs-literal">true</span>

[*]

indent_size = <span class="hljs-number">4</span>
indent_style = space
end_of_line = lf
insert_final_newline = <span class="hljs-literal">true</span>

 <span class="hljs-comment">// Set root to true: A search for .editorconfig files will stop if the root file path is reached or an EditorConfig file with root=true is found.</span>

 <span class="hljs-comment">//[*]: Except for path selectors, it matches any string of characters.</span>

 <span class="hljs-comment">//indent_size: Indent size is set to 4. </span>
 <span class="hljs-comment">//Indent_style: set to space</span>
 <span class="hljs-comment">//end_of_line: Set to lf</span>
<span class="hljs-comment">//insert_final_newline: Set to true</span>
</code></pre>
<p>To know more about the wildcards pattern, visit the <a target="_blank" href="https://editorconfig.org/#file-format-details">EditorConfig docs</a>.</p>
<p>Using ESLint and EditorConfig together can help to spot potential issues early. It also ensures that your code is consistent, maintainable, and of high quality.</p>
<p>The combination of ESLint and EDitorConfig saves you time on code maintenance and debugging.</p>
<h3 id="heading-features-of-eslint">Features of ESLint</h3>
<ol>
<li>Configurable: ESLint allows you to customize and add your own rules to the configuration file.</li>
<li>Support ECMAScript: ESLint ensures your code is compatible with the latest language features.</li>
<li>Supports many file formats: ESLint can analyze JavaScript code in a variety of file formats, including but not limited to .js, .jsx, and .vue.</li>
<li>Integration: ESLint integrates seamlessly with Webpack and Gulp, which are popular build tools.</li>
</ol>
<h3 id="heading-eslint-formatting-rules">ESLint Formatting Rules</h3>
<p>Some of the popular formatting rules in ESLint are listed below:</p>
<ol>
<li>Indentation: ESLint by default expects a four-space per level indent. But you can customize this using the popular <code>--fix</code> option.</li>
<li>Semicolons: ESLint enforces the use of semicolons at the end of each statement. This rule is set to "always" by default. Use the popular <code>--fix</code> option to reset it to "never".</li>
<li>Line wrap: Use the <code>max-len</code> rule to change the maximum line length from the default 80 to your preferred  value.</li>
<li>Quotes: The quotes rule can be changed from the default value of "single" to "double" using the <code>--fix</code> option.</li>
</ol>
<h3 id="heading-pros-of-eslint">Pros of ESLint</h3>
<ol>
<li>Saves time: ESLint saves time by reducing the amount of time spent on manual code reviews and debugging.</li>
<li>Active Community: ESLint has a wide and active community base that contributes to the development of the tool and its ecosystem.</li>
<li>Code analyzer: ESLint analyze your code to quickly find problems.</li>
<li>Consistency: ESLint helps in maintaining clean and readable code by enforcing a consistent coding style.</li>
</ol>
<h3 id="heading-cons-of-eslint">Cons of ESLint</h3>
<ol>
<li>Rule conflicts: With a large set of rules, ESLint rules can sometimes conflict with one another, resulting in more configuration and fine-tuning.</li>
<li>Steeper learning curve: ESLint has a pretty steep learning curve, as it has many rules and learning how to configure them can take time.</li>
<li>False positives: ESLint can sometimes flag code as problematic code even when it is correct, which can be frustrating for developers.</li>
</ol>
<h2 id="heading-overview-of-js-beautifier">Overview of JS Beautifier</h2>
<p><a target="_blank" href="https://beautifier.io/">JavaScript Beautifier</a>, also known as js-beautify, is an open-source, cross-platform command-line tool. It is a beautifier for re-formating and re-indenting bookmarklets, ugly JavaScript, and it partly deobfuscates scripts.</p>
<p>You can install JS beautifier both locally and globally.</p>
<p>Run <code>npm -g install js-beautify</code> to install globally, and <code>npm install js-beautify</code> to install locally.</p>
<p>You can configure it through the command line option.</p>
<p>After local installation, you can import and call the appropriate beautifier methods for JS, CSS, or HTML. An example of how to call the methods goes like this: beautify (<code>code</code>, <code>options</code>).</p>
<p>While <code>code</code> is the string of code to be beautified, <code>options</code> is an object with the settings you would like used to beautify the code. See the example below for a JavaScript script file:</p>
<pre><code>npx beautify(<span class="hljs-string">"script.js"</span>,{<span class="hljs-attr">indent_size</span>:<span class="hljs-number">4</span>})
</code></pre><p>You can also configure it through a configuration file:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"indent_size"</span>: <span class="hljs-number">4</span>,
  <span class="hljs-attr">"indent_char"</span>: <span class="hljs-string">" "</span>,
  <span class="hljs-attr">"indent_with_tabs"</span>: <span class="hljs-literal">false</span>,
  <span class="hljs-attr">"brace_style"</span>: <span class="hljs-string">"collapse"</span>
}
</code></pre>
<p>Create a file <code>.jsbeautifyrc</code> in the root directory of your project. This option will override the default option of JS beautifier. You can also use Beautifier on your web browser. Learn more about <a target="_blank" href="https://www.npmjs.com/package/js-beautify">JSbeautifer from its docs here</a>.</p>
<h3 id="heading-feature-of-js-beautifier">Feature of JS Beautifier</h3>
<ol>
<li>Formatting: You can customize JS Beautifier to fit your personal preferences and coding style because it offers varieties of formatting options, such as indentation size and braces style.</li>
<li>Online version: You can beautify JavaScript using JS Beautifier in your web browser, just as you can on the command line.</li>
</ol>
<h3 id="heading-js-beautifier-formatting-rules">JS Beautifier Formatting Rules</h3>
<ol>
<li>Indentation: The default identation in JS Beautifier is 4 spaces, but you can change it to 2 or 8 spaces, or use tabs instead. Use the <code>indent_size</code> option to specify the number of spaces to use for indentation.</li>
<li>Semicolons: You can change your semicolon settings in JS Beautifier with the <code>semicolon</code> option. You change this by alternating the value of the semicolon option between "true" or "false".</li>
<li>Line wrap: Use the <code>max_char</code> option to limit each line to 80 characters. You can set the value of the max_char to 80 or any other preferred  number.</li>
</ol>
<h3 id="heading-pros-of-js-beautifier">Pros of JS Beautifier</h3>
<ol>
<li>Time-saving: JS Beautifier saves time. It automates the many steps of formatting and organizing code.</li>
<li>Online presence: JS Beautifier's online presence is a game changer, as a lot of non-developers will be able to use it.</li>
<li>Detects errors: JS Beautifier helps catch small errors that can be difficult to spot otherwise.</li>
<li>Integration: JS Beautifier's compatibility with varieties of code editors and IDEs makes it a versatile tool.</li>
</ol>
<h3 id="heading-cons-of-js-beautifier">Cons of JS Beautifier</h3>
<ol>
<li>Complexity: Despite having an online version, JS Beautifier is somewhat complex for beginners.</li>
<li>Potential for over-formatting: In some cases, JS Beautifier may make the code harder to read because of over-formatting.</li>
</ol>
<h2 id="heading-results-from-all-the-formatting-tools">Results from all the Formatting Tools</h2>
<p>We'll use the code sample below to test how these four popular tools format code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">7</span>]

          <span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">'kamal'</span>, <span class="hljs-string">'lawal'</span>, <span class="hljs-string">"shola"</span>, <span class="hljs-string">"olaide"</span>];
</code></pre>
<p>As you can see, this code isn't properly formatted. So let's try the tools to see how they help.</p>
<h3 id="heading-formatting-example-with-jsfmt">Formatting example with JsFmt</h3>
<p>Using the above code as a sample, the command <code>npx jsfmt --write "Your file"</code> will format the code to this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">7</span>]

<span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">'kamal'</span>, <span class="hljs-string">'lawal'</span>, <span class="hljs-string">"shola"</span>, <span class="hljs-string">"olaide"</span>];
</code></pre>
<p>As you can see, there is a noticeable change in the code, and you can configure this to your desired taste.</p>
<h3 id="heading-formatting-example-with-standardjs">Formatting example with StandardJS</h3>
<p>By running the popular <code>npx standard--fix</code> command from the terminal, you will have the following result.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">7</span>]

<span class="hljs-keyword">const</span> peoples = [<span class="hljs-string">'kamal'</span>, <span class="hljs-string">'lawal'</span>, <span class="hljs-string">'shola'</span>, <span class="hljs-string">'olaide'</span>]
</code></pre>
<p>Notice the code was properly formatted, most especially the elements with double quotes within the <code>peoples</code> array.</p>
<h3 id="heading-formatting-example-with-eslint">Formatting example with ESLint</h3>
<p>Using the same code as above, the <code>npx eslint "Your file name --fix"</code> command will quickly format to this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">7</span>]

<span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">'kamal'</span>,<span class="hljs-string">'lawal'</span>,<span class="hljs-string">'shola'</span>,<span class="hljs-string">'olaide'</span>]
</code></pre>
<p>You can also change the configuration of the tool, by changing the elements of the <code>peoples</code> array so they're inside double quotes:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">8</span>,<span class="hljs-number">9</span>,<span class="hljs-number">7</span>]

<span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">"kamal"</span>,<span class="hljs-string">"lawal"</span>,<span class="hljs-string">"shola"</span>,<span class="hljs-string">"olaide"</span>];
</code></pre>
<p>You can do this by going to the .eslintrc file and manipulating the rules like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"quotes"</span>: [<span class="hljs-string">"error"</span>, <span class="hljs-string">"double"</span>],
  <span class="hljs-attr">"semi"</span>: [<span class="hljs-string">"off"</span>, <span class="hljs-string">"always"</span>]
}
</code></pre>
<h3 id="heading-formatting-example-with-js-beautifier">Formatting example with JS Beautifier</h3>
<p>Here's the result from JS Beautifier for the same code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> numbers = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">7</span>]
<span class="hljs-keyword">let</span> peoples = [<span class="hljs-string">'kamal'</span>, <span class="hljs-string">'lawal'</span>, <span class="hljs-string">"shola"</span>, <span class="hljs-string">"olaide"</span>];
</code></pre>
<p>You can configure it more from your JSON file if you wish.</p>
<p>Now you've seen these formatters in action!</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this guide, we talked about some alternatives to using Prettier. We discussed Jsfmt, ESlint, StandardJS, and JS Beautifier, as well as their features, pros, and cons.</p>
<p>I hope you are now more equipped to choose the right linter/formatter for your coding projects.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Add Commit Hooks to Git with Husky to Automate Code Tasks ]]>
                </title>
                <description>
                    <![CDATA[ There are a lot of tools to automate our code tasks. We can check for syntax issues with ESLint and format our code with Prettier.  But not everyone on the team will remember to run those commands every time they commit. How can we use Husky to add G... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-add-commit-hooks-to-git-with-husky-to-automate-code-tasks/</link>
                <guid isPermaLink="false">66b8e335684cb75ad7f76d18</guid>
                
                    <category>
                        <![CDATA[ automation ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Git ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Colby Fayock ]]>
                </dc:creator>
                <pubDate>Wed, 14 Oct 2020 15:58:01 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/10/husky.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>There are a lot of tools to automate our code tasks. We can check for syntax issues with ESLint and format our code with Prettier. </p>
<p>But not everyone on the team will remember to run those commands every time they commit. How can we use Husky to add Git hooks to run them for us?</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-are-git-hooks">What are Git Hooks?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-husky">What is Husky?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-we-going-to-build">What are we going to build?</a></li>
<li><a class="post-section-overview" href="#step-0-setting-up-a-new-project">Step 0: Setting up a new project</a></li>
<li><a class="post-section-overview" href="#step-1-installing-husky-to-a-project">Step 1: Installing Husky to a project</a></li>
<li><a class="post-section-overview" href="#step-2-configuring-husky-to-run-git-hooks">Step 2: Configuring Husky to run Git hooks</a></li>
<li><a class="post-section-overview" href="#step-3-using-husky-to-format-code-with-prettier">Step 3: Using Husky to format code with Prettier</a></li>
</ul>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/tuzys2b1J70" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<h2 id="heading-what-are-git-hooks">What are Git Hooks?</h2>
<p><a target="_blank" href="https://git-scm.com/docs/githooks">Git hooks</a> are scripts that you can set up to <a target="_blank" href="https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks">run at certain events</a> in the Git lifecycle. These events include different stages of a commit, like before a commit (pre-commit) and after a commit (post-commit).</p>
<p>These are useful in that they allow developers to run custom code tasks or even enforce standards by automating other scripts to run those tasks.</p>
<h2 id="heading-what-is-husky">What is Husky?</h2>
<p><a target="_blank" href="https://github.com/typicode/husky">Husky</a> is a tool that allows us to easily wrangle Git hooks and run the scripts we want at those stages.</p>
<p>It works by including an object right within our <code>package.json</code> file that configures Husky to run the scripts we specify. After that, Husky handles managing at which point in the Git lifecycle our scripts will run.</p>
<h2 id="heading-what-are-we-going-to-build">What are we going to build?</h2>
<p>We’re going to set up a simple project that we can use to test out Git hooks.</p>
<p>While you should be able to follow along with any project that you’re working with, I’m going to use <a target="_blank" href="https://nextjs.org/">Next.js</a> as the starting point for this project, simply for the fact that we can run a single command to get a project started.</p>
<p>One consideration about following along with this project, though, is that we’ll use <a target="_blank" href="https://prettier.io/">Prettier</a> as an example of what you can do with Git hooks. </p>
<p>Prettier is a tool that will automatically format our code for us, which if you’re not expecting that to happen, can cause a lot of stress. Following along with me using the Next.js project will allow you to test this out without making any unintentional changes.</p>
<p>As for testing the Git hooks, we’ll start by adding a simple command line statement to see Husky work. But we’ll also test out adding Prettier, which will automatically format our code for us.</p>
<p>Finally, at the time of writing this, Husky released an <a target="_blank" href="https://typicode.github.io/husky/#/">v5 Alpha</a> version of their Git hook solution. Given it’s still just an Alpha version, we’re going to move forward with <a target="_blank" href="https://github.com/typicode/husky/tree/v4.3.0">v4</a>, which allows us to easily install Husky with npm.</p>
<h2 id="heading-step-0-how-to-set-up-a-new-project">Step 0: How to set up a new project</h2>
<p>As I mentioned, you can really follow the same steps here with any project that’s managed with a <code>package.json</code> file. </p>
<p>Next.js is absolutely overkill for this walkthrough, but the goal is to minimize the steps for getting set up to actually work with Husky.</p>
<p>To get started with Next.js, navigate to the directory you want to start your project in and run the following:</p>
<pre><code>yarn create next-app my-husky-project
# or
npx create-next-app my-husky-project
</code></pre><p><em>Note: feel free to replace <code>my-husky-project</code> to whatever you’d like to name your directory.</em></p>
<p>This will create a new folder, create a new Next.js project, and install all the dependencies.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/create-next-app.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Once it’s done, navigate to that new folder, and we should be ready to go!</p>
<p><a target="_blank" href="https://github.com/colbyfayock/my-husky-project/commit/9e0b39c8f34c2755e074a32ef9de8d4047b68f67">Follow along with the commit</a>.</p>
<h2 id="heading-step-1-how-to-install-husky-to-a-project">Step 1: How to install Husky to a project</h2>
<p>To install Husky, we can use yarn or npm.</p>
<pre><code>yarn add husky
# or
npm install husky
</code></pre><p><em>Note: if installing Husky at this point installs v5, that means v5 has been officially released. Please see the <a target="_blank" href="https://typicode.github.io/husky/#/">updated Husky documentation</a> or you can install the latest v4 version by specifying husky@4.3.0 (or whatever the latest version is) when installing.</em></p>
<p>Once the package is finished installing, we should be ready to go with Husky.</p>
<p><a target="_blank" href="https://github.com/colbyfayock/my-husky-project/commit/720728cd595d41c9197640bd4c48e9133bd7d956">Follow along with the commit</a>.</p>
<h2 id="heading-step-2-how-to-configure-husky-to-run-git-hooks">Step 2: How to configure Husky to run Git hooks</h2>
<p>Next, we’re going to set up Husky so we can use it for our Git hooks.</p>
<p>Inside of our <code>package.json</code> file, create a new property called <code>husky</code> with an empty object.</p>
<pre><code class="lang-json"><span class="hljs-string">"husky"</span>: {},
</code></pre>
<p>You can add this really wherever you want in the <code>package.json</code> file, but I’m going to add it right below the <code>scripts</code>  property so I can more easily manage them together.</p>
<p>Inside of that, we want to add another property called <code>hooks</code> that also specifies an empty object:</p>
<pre><code class="lang-json"><span class="hljs-string">"husky"</span>: {
  <span class="hljs-attr">"hooks"</span>: {}
},
</code></pre>
<p>This is where we’re going to add our Git hooks. Husky supports pretty much <a target="_blank" href="https://git-scm.com/docs/githooks">all Git hooks defined by Git</a>, so we can be as flexible we would like within our Git event flow.</p>
<p>To test this out, I created <a target="_blank" href="https://github.com/colbyfayock/my-husky-project/tree/main+test">a new branch</a> where I literally added every Git hook from that page including a script that simply writes to the terminal <code>[Husky] event name</code>.</p>
<p><em>Note: don’t feel like you need to do this unless you’re curious. The goal is to be able to show you with my example how it works.</em></p>
<pre><code>“husky”: {
  “hooks”: {
    “applypatch-msg”: “echo \”[Husky] applypatch-msg\””,
    “pre-applypatch”: “echo \”[Husky] pre-applypatch\””,
    “post-applypatch”: “echo \”[Husky] post-applypatch\””,
    “pre-commit”: “echo \”[Husky] pre-commit\””,
</code></pre><p>What this will do is tell Husky that at every single stage where we’re permitted to hook into Git, tell us!</p>
<p>When I commit that change, we can immediately see that Husky fires off some of our scripts.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/husky-commit-hooks.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>These are all of the events that Git allows us to hook into that happen during the commit process.</p>
<p>And similarly, if I push those changes out to Github, I can see that the push process runs the <code>pre-push</code> hook!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/husky-push-hooks.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You may never use most of the hooks that Husky and Git provide (we only saw a few between those two commands). </p>
<p>But it’s awesome to be able to see how powerful this can be, whether it’s running code that formats our code, prevents secret access keys from being committed, or really anything else that can help automate important tasks to your workflow.</p>
<p>We can now see that we can configure Husky by specifying the configuration and the hooks right in our <code>package.json</code>.</p>
<p><a target="_blank" href="https://github.com/colbyfayock/my-husky-project/commit/108583a7e96564baf0fac994eafa6cf98d65d03e">Follow along with the commit</a>.</p>
<p><em>Note: If you want to check out my branch that includes every Git hook to test with, <a target="_blank" href="https://github.com/colbyfayock/my-husky-project/tree/main+test">you can find it on Github</a>.</em></p>
<h2 id="heading-step-3-how-to-use-husky-to-format-code-with-prettier">Step 3: How to use Husky to format code with Prettier</h2>
<p>Finally, for a real-world use case, we’re going to test out using Prettier to automatically format our code.</p>
<p>Prettier is an opinionated code formatting tool that allows you to easily clean up your code to make it look like a single person wrote it.</p>
<p>Why are tools like Prettier important? When working through code, especially with a team, it’s important to maintain consistency so everyone knows what to expect. It will help prevent arguing over a semi-colon in a code review, but it will also help catch syntax errors and prevent bugs.</p>
<p><em>Warning: running Prettier will automatically format all of your code. While we’re going to test this out before committing the changes, once you apply this as a Git Hook, it will automate this process.</em></p>
<p>To get started with Prettier, let’s install it with our package manager:</p>
<pre><code>yarn add prettier -D
# or
npm install prettier --save-dev
</code></pre><p><em>Note: we’re installing Prettier as a <code>devDependency</code> as our application doesn’t need this to run.</em></p>
<p>Next, we can add a new script in our <code>package.json</code> that will make it easier to run Prettier to test this out.</p>
<p>Inside the <code>scripts</code> property, add:</p>
<pre><code class="lang-json"><span class="hljs-string">"lint"</span>: <span class="hljs-string">"prettier --check ."</span>
</code></pre>
<p>For this first test, we’re going to run it as a “check” which will allow us to see which files would change.</p>
<p>Run the following:</p>
<pre><code>yarn lint
# or 
npm run lint
</code></pre><p>And once we do, we can see that Prettier is telling us that would change the files listed.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/prettier-check.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>At this point, our code will remain unchanged. But if we want to run Prettier for real to make those changes, we can first add an additional script:</p>
<pre><code class="lang-json"><span class="hljs-string">"format"</span>: <span class="hljs-string">"prettier --write ."</span>
</code></pre>
<p>And if we run that script, it will update all of those files to format the code to Prettier’s specification.</p>
<p><em>Warning: just another note, running Prettier to write the changes will make changes in your files. These are all code-style changes that shouldn’t impact how the code runs, but how the code looks. Before running format, you should save any changes by committing with Git so that you can easily revert the changes if you’re not happy with them.</em></p>
<p>You can now run the script with:</p>
<pre><code>yarn format
</code></pre><p>And we can see that Prettier updated our files!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/prettier-write.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now the part that’s relevant to this walkthrough: we can add this as a Git hook. This way, when someone tries to commit code, Prettier is run before the code is saved. This means that we’ll always keep code consistent with Prettier’s formatting style.</p>
<p>Inside our Husky hooks configuration, let’s add:</p>
<pre><code class="lang-json"><span class="hljs-string">"husky"</span>: {
  <span class="hljs-attr">"hooks"</span>: {
    <span class="hljs-attr">"pre-commit"</span>: <span class="hljs-string">"prettier --write . &amp;&amp; git add -A ."</span>
  }
},
</code></pre>
<p>If you notice in our pre-commit hook, we’re also adding <code>git add -A .</code>. </p>
<p>When Husky runs, it simply runs the script provided. When running our Prettier command, we’re only formatting the code, but we never save those changes as part of the process. So we use <code>git add</code> to store all of those changes and include them in the commit.</p>
<p>To test this out, I reverted the changes to all of the files that were formatted before. If you’re following along with the same project, you can run:</p>
<pre><code>git checkout pages
</code></pre><p>Which will reset all of the changes in <code>pages</code> to the last commit.</p>
<p>Now, let’s try to add all of our files with Git and commit the changes.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/10/git-commit-husky-precommit-prettier.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>And once we run our commit command, we can see that the Husky pre-commit hook kicks in already and formats our code!</p>
<p><a target="_blank" href="https://github.com/colbyfayock/my-husky-project/commit/315112d062a791f20eda11f9c608c5fa794ba73e">Follow along with the commit</a>.</p>
<h2 id="heading-what-can-i-do-next">What can I do next?</h2>
<h3 id="heading-use-lint-staged-to-only-run-formatting-on-changed-files">Use lint-staged to only run formatting on changed files</h3>
<p>We’re using Prettier right in our pre-commit hook and specifying <code>.</code> which means it’s going to run on all files every time.</p>
<p>We can use a tool called <a target="_blank" href="https://github.com/okonet/lint-staged">lint-staged</a>, which allows us to still run our Git hooks with Husky, but it will only run on files that are staged.</p>
<p>For instance, if we wanted to do this with Husky and Prettier, our configuration might look like:</p>
<pre><code><span class="hljs-string">"husky"</span>: {
  <span class="hljs-string">"hooks"</span>: {
    <span class="hljs-string">"pre-commit"</span>: <span class="hljs-string">"lint-staged"</span>
  }
},
<span class="hljs-string">"lint-staged"</span>: {
  <span class="hljs-string">"*"</span>: <span class="hljs-string">"prettier --write"</span>
},
</code></pre><p>As part of how lint-staged runs, it will attach the changed files to the end of our Prettier statement automatically for us.</p>
<p>You’ll also notice we didn't include <code>git add</code>. lint-staged will also add any changes to Git for us automatically.</p>
<h3 id="heading-set-up-a-prettier-config-to-customize-formatting-rules">Set up a Prettier config to customize formatting rules</h3>
<p>Prettier is very opinionated. There are some things I personally don’t prefer and you might feel the same.</p>
<p>Luckily, Prettier allows you to set up a configuration file that can override some of those files to make your code just the way you and your team want it.</p>
<h3 id="heading-tell-prettier-to-ignore-files-with-prettierignore">Tell Prettier to ignore files with .prettierignore</h3>
<p>You also probably don’t want Prettier running on “all the things” (maybe you do).</p>
<p>Prettier allows you to set up a <code>.prettierignore</code>  file right inside of the root of the project next to <code>package.json</code>, similar to <code>.gitignore</code>, that allows you to tell Prettier what files it should not run on.</p>
<div id="colbyfayock-author-card">
  <p>
    <a href="https://twitter.com/colbyfayock">
      <img src="https://res.cloudinary.com/fay/image/upload/w_2000,h_400,c_fill,q_auto,f_auto/w_1020,c_fit,co_rgb:007079,g_north_west,x_635,y_70,l_text:Source%20Sans%20Pro_64_line_spacing_-10_bold:Colby%20Fayock/w_1020,c_fit,co_rgb:383f43,g_west,x_635,y_6,l_text:Source%20Sans%20Pro_44_line_spacing_0_normal:Follow%20me%20for%20more%20JavaScript%252c%20UX%252c%20and%20other%20interesting%20things!/w_1020,c_fit,co_rgb:007079,g_south_west,x_635,y_70,l_text:Source%20Sans%20Pro_40_line_spacing_-10_semibold:colbyfayock.com/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_68,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_145,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_222,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_295,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/v1/social-footer-card" alt="Follow me for more Javascript, UX, and other interesting things!" width="2000" height="400" loading="lazy">
    </a>
  </p>
  <ul>
    <li>
      <a href="https://twitter.com/colbyfayock">? Follow Me On Twitter</a>
    </li>
    <li>
      <a href="https://youtube.com/colbyfayock">? Subscribe To My Youtube</a>
    </li>
    <li>
      <a href="https://www.colbyfayock.com/newsletter/">✉️ Sign Up For My Newsletter</a>
    </li>
    <li>
      <a href="https://github.com/sponsors/colbyfayock">? Sponsor Me</a>
    </li>
  </ul>
</div>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Don’t just lint your code - fix it with Prettier ]]>
                </title>
                <description>
                    <![CDATA[ Linting makes our lives easier because it tells us what’s wrong with our code. But how can we avoid doing the actual work that goes into fixing it? Previously I wrote about linting, what it is, and how it makes your life easier. At the end, I actuall... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/dont-just-lint-your-code-fix-it-with-prettier/</link>
                <guid isPermaLink="false">66b8e322682e4a25eed26199</guid>
                
                    <category>
                        <![CDATA[ clean code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Code Quality ]]>
                    </category>
                
                    <category>
                        <![CDATA[ code review ]]>
                    </category>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ front end ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ frontend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Colby Fayock ]]>
                </dc:creator>
                <pubDate>Wed, 06 Nov 2019 15:45:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/11/formatting-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Linting makes our lives easier because it tells us what’s wrong with our code. But how can we avoid doing the actual work that goes into fixing it?</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/what-is-linting-and-how-can-it-save-you-time/">Previously I wrote about linting</a>, what it is, and how it makes your life easier. At the end, I actually included a way that you could automatically fix your code. So why am I writing this?</p>
<h2 id="heading-what-do-you-mean-fix-it"><strong>What do you mean fix it?</strong></h2>
<p>Before we roll into it, let’s hit this quick. Linters are powerful and provide an easy way to scan your code for syntax errors that could lead to bugs. Or they can simply help keep a codebase clean, healthy, and consistent. When run, it will show all the issues and let you go through each one individually to fix them.</p>
<p>Taking that to the next level, some linters will actually allow you to pass in an argument to the command running the linter that allows it to fix it for you automagically. This means you don’t have to manually go through and make all of those little whitespace and semicolon (add them! ?) tweaks yourself!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/ron-swanson-happy.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Ron Swanson happy</em></p>
<h2 id="heading-so-what-more-can-i-do-to-fix-things"><strong>So what more can I do to fix things?</strong></h2>
<p>If you already use the fix option, thats a good start. But there are tools out there that have been developed specifically to tackle this problem beyond just a flag into your command. The one I’m going to cover is Prettier.</p>
<h2 id="heading-what-is-prettier"><strong>What is Prettier?</strong></h2>
<p><a target="_blank" href="https://prettier.io/">Prettier</a> pegs itself as “an opinionated code formatter." It takes an input of your code and outputs it in a consistent format stripping any of the original code style. It actually converts your code to a <a target="_blank" href="https://github.com/benjamn/recast">syntax tree</a>, then rewrites it using the styles and rules you and Prettier provide together via your ESLint config and Prettier’s default rules.</p>
<p>You can easily use Prettier alone just to format your code, which works just fine. But if you combine this with an underlying ESLint process, you get both a powerful linter and a powerful fixer. I’m going to show you how to make those work together.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/voltron.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Voltron</em></p>
<h2 id="heading-getting-started-with-prettier"><strong>Getting started with Prettier</strong></h2>
<p>For this walkthrough, I’m going to assume that you have ESLint set up and configured in an application. Particularly, I’m going to pick up where I left off in my previous walkthrough where <a target="_blank" href="https://www.freecodecamp.org/news/what-is-linting-and-how-can-it-save-you-time/">we installed ESLint to a React application</a>.</p>
<p>Additionally of note, Prettier tells us right from the start that it's an opinionated code formatter. You should expect that it will format your code in a consistent way, but maybe a different way than you currently have it configured. But don’t fret! You can tweak this configuration.</p>
<p>So what are we starting off with? We already:</p>
<ul>
<li>Have installed <a target="_blank" href="https://github.com/eslint/eslint">ESLint</a></li>
<li>Have added <a target="_blank" href="https://github.com/babel/babel-eslint">Babel</a> as our parser</li>
<li>Have added a <a target="_blank" href="https://github.com/yannickcr/eslint-plugin-react">plugin</a> that includes React configurations</li>
</ul>
<p>Next, let’s get started by installing a few packages:</p>
<pre><code class="lang-shell">yarn add prettier prettier-eslint prettier-eslint-cli -D
</code></pre>
<p><em>Note: the command above is similar to using <code>npm</code>. If your project doesn't use <code>yarn</code>, swap out to <code>npm</code> as appropriate.</em></p>
<p>Above, we’re installing:</p>
<ul>
<li><a target="_blank" href="https://github.com/prettier/prettier">prettier</a>: core Prettier package and engine</li>
<li><a target="_blank" href="https://github.com/prettier/prettier-eslint">prettier-lint</a>: passes the Prettier result to ESLint to fix using your ESLint config</li>
<li><a target="_blank" href="https://github.com/prettier/prettier-eslint-cli">prettier-eslint-cli</a>: helps Prettier and ESLint work together on various files across your project</li>
</ul>
<p>And we’re installing them as a dev dependency, as we don’t need it outside development.</p>
<h2 id="heading-configuring-your-new-formatter"><strong>Configuring your new formatter</strong></h2>
<p>Now that our packages are installed, we can set up <code>yarn</code> to run this command for us.</p>
<p>Previously, we set up a <code>lint</code> script to look like this in our <code>package.json</code>:</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
  ...
  <span class="hljs-attr">"lint"</span>: <span class="hljs-string">"eslint . --ext .js"</span>
  ...
}
</code></pre>
<p>We’re going to leave that as it is, but we’ll do something similar and create a new script right next to it called <code>format</code> for our formatter Prettier:</p>
<pre><code class="lang-json"><span class="hljs-string">"scripts"</span>: {
  ...
  <span class="hljs-attr">"format"</span>: <span class="hljs-string">"prettier-eslint --eslint-config-path ./.eslintrc.js --write '**/*.js'"</span>,
  <span class="hljs-attr">"lint"</span>: <span class="hljs-string">"eslint . --ext .js"</span>
  ...
}
</code></pre>
<p>So what’s going on there? We’re:</p>
<ul>
<li>Adding a new script called <code>format</code>, that we can run as <code>yarn format</code></li>
<li>We’re utilizing our <code>prettier-eslint-cli</code> package to run the formatting for us</li>
<li>We’re passing in our ESLint config located next to our <code>package.json</code> in the root of the project (change this if it’s in a different location)</li>
<li>And finally, we’re telling prettier to write all files matching <code>**/*.js</code>, or any JS files it finds recursively through our project</li>
</ul>
<p>The beauty here is that we're passing in our ESLint config to Prettier. This means we only have to maintain 1 config for both tools, but we still leverage the linting power of ESLint along with the formatting power of Prettier.</p>
<h2 id="heading-run-your-formatter"><strong>Run your formatter!</strong></h2>
<p>Now that we’re all set up, let’s run it! Run this following:</p>
<pre><code>yarn format
</code></pre><p>and immediately, we see that it works:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/prettier-command-line-success.png" alt="Image" width="600" height="400" loading="lazy">
<em>Successfully running Prettier</em></p>
<h2 id="heading-hey-my-code-looks-different"><strong>Hey, my code looks different!</strong></h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/spongebob-pitchforks.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Angry mob with pitchforks</em></p>
<p>As I mentioned earlier, Prettier tells us straight up, it’s an opinionated formatter. It ships with its own rules, sort of like its own ESLint config, so it will go through and make those changes as well.</p>
<p>Don’t abandon your code! Instead, you can review the changes, see if maybe it makes sense to keep it that way (it will be very consistent) or you can update your ESLint config (<code>.eslintrc.js</code>) to overwrite the rules you don’t like. This is also a good way to maybe learn some new things that you might not have expected to get caught before.</p>
<h2 id="heading-so-where-does-this-leave-us"><strong>So where does this leave us?</strong></h2>
<p>If you’ve followed along so far, we now have two commands:</p>
<ul>
<li><code>lint</code>: which will check your code for you and tell you what's wrong</li>
<li><code>format</code>: will automatically try to fix the problems for you</li>
</ul>
<p>When using these in practice, your best bet is to always run <code>format</code> first to let it try to automatically fix anything it can. Then immediately run <code>lint</code> to catch anything Prettier wasn’t able to fix automatically.</p>
<h2 id="heading-whats-next"><strong>What’s next?</strong></h2>
<p>Now that we can format our code automatically, we should be able to fix our code automatically!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/11/fresh-off-the-boat-mind-blown.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Eddie from Fresh Off the Boat's mind blown</em></p>
<p>Next time we’ll take this a step further and set up a <code>git</code> hook that will allow this to run before you commit. This means you won't ever have to worry about forgetting to run this again!</p>
<div id="colbyfayock-author-card">
  <p>
    <a href="https://twitter.com/colbyfayock">
      <img src="https://res.cloudinary.com/fay/image/upload/w_2000,h_400,c_fill,q_auto,f_auto/w_1020,c_fit,co_rgb:007079,g_north_west,x_635,y_70,l_text:Source%20Sans%20Pro_64_line_spacing_-10_bold:Colby%20Fayock/w_1020,c_fit,co_rgb:383f43,g_west,x_635,y_6,l_text:Source%20Sans%20Pro_44_line_spacing_0_normal:Follow%20me%20for%20more%20JavaScript%252c%20UX%252c%20and%20other%20interesting%20things!/w_1020,c_fit,co_rgb:007079,g_south_west,x_635,y_70,l_text:Source%20Sans%20Pro_40_line_spacing_-10_semibold:colbyfayock.com/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_68,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_145,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_222,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_295,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/v1/social-footer-card" alt="Follow me for more Javascript, UX, and other interesting things!" width="2000" height="400" loading="lazy">
    </a>
  </p>
  <ul>
    <li>
      <a href="https://twitter.com/colbyfayock">? Follow Me On Twitter</a>
    </li>
    <li>
      <a href="https://youtube.com/colbyfayock">?️ Subscribe To My Youtube</a>
    </li>
    <li>
      <a href="https://www.colbyfayock.com/newsletter/">✉️ Sign Up For My Newsletter</a>
    </li>
  </ul>
</div>

<p><em>Originally published at <a target="_blank" href="https://www.colbyfayock.com/2019/11/dont-just-lint-your-code-fix-it-with-prettier/">https://www.colbyfayock.com/2019/11/dont-just-lint-your-code-fix-it-with-prettier/</a></em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to integrate Prettier with ESLint and stylelint ]]>
                </title>
                <description>
                    <![CDATA[ By Abhishek Jain or How to never worry about code styling again _Photo by [Unsplash](https://unsplash.com/photos/bJjsKbToY34?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" rel="noopener" target="_blank" title="">NordWood Themes ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/integrating-prettier-with-eslint-and-stylelint-99e74fede33f/</link>
                <guid isPermaLink="false">66c3581f71e87702d4e5b6de</guid>
                
                    <category>
                        <![CDATA[ eslint ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Prettier ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 30 Jul 2018 06:23:11 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*4rTkzZ0psMNKu9RgpEfQmg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Abhishek Jain</p>
<h4 id="heading-or-how-to-never-worry-about-code-styling-again">or How to never worry about code styling again</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/2NnxX8zdoJFw9uQM9ez2epHwX3Z26IQQjmt-" alt="Image" width="800" height="533" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/photos/bJjsKbToY34?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="_blank" title=""&gt;NordWood Themes on &lt;a href="https://unsplash.com/search/photos/computer?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title=")</em></p>
<p><a target="_blank" href="https://github.com/eslint/eslint">ESLint</a> and <a target="_blank" href="https://github.com/stylelint/stylelint">stylelint</a> are really amazing tools that allow you to enforce coding patterns among your teams. This has many benefits, like outputting better and more consistent code, getting rid of useless diffs in commits (newline, indentation, et al.) among many others.</p>
<p>But over time, this can prove to be a bit of a hassle among the developers of a team, who find it an extra mental burden to manually add semicolons, newlines, indentations, etc just to conform to the lint rules. This is where a code formatting tool like <a target="_blank" href="https://github.com/prettier/prettier">Prettier</a> comes in.</p>
<p>Prettier can be set up to automatically format your code according to some specified rules. If you are using VSCode, you can even have your code be formatted whenever you hit save (I’m sure there must ways to set this up in other editors but I haven’t looked into it.)</p>
<p>However, you don’t want to create a new Prettier config file, since you already have all the formatting related rules specified in your ESLint and stylelint config files. So, we will need some magic for that. ✨</p>
<p>Let’s now dive into a step by step of how to set this all this up, and also how to format all of your existing code according to the lint rules. This guide assumes that your project already has ESLint and stylelint set up with their <code>.eslintrc</code> and <code>.stylelintrc</code> files.</p>
<h3 id="heading-part-1-formatting-the-existing-codebase">PART 1: Formatting the existing codebase</h3>
<h4 id="heading-step-1"><strong>Step 1</strong></h4>
<p>Install <a target="_blank" href="https://github.com/prettier/prettier-eslint">prettier-eslint</a>, which is a tool that formats your JavaScript using Prettier followed by <code>eslint --fix</code>. The <code>--fix</code> is an ESLint feature that attempts to automatically fix some problems for you.</p>
<pre><code>npm install --save-dev prettier-eslint
</code></pre><p>This tool infers the equivalent Prettier config options from your existing <em>.eslintrc</em> file. So you shouldn’t need to create a new <em>.prettierrc</em> file in most cases.</p>
<h4 id="heading-step-2"><strong>Step 2</strong></h4>
<p>Install <a target="_blank" href="https://github.com/prettier/prettier-eslint-cli">prettier-eslint-cli</a>. This is the CLI tool that’ll help you run all of your files through prettier-eslint at once.</p>
<pre><code>npm install --save-dev prettier-eslint-cli
</code></pre><h4 id="heading-step-3"><strong>Step 3</strong></h4>
<p>Install <a target="_blank" href="https://github.com/hugomrdias/prettier-stylelint">prettier-stylelint</a>, which is a tool that formats your CSS/SCSS with Prettier followed by <code>stylelint —-fix</code>. Like ESLint, <code>--fix</code> is a stylelint feature that attempts to automatically fix some problems for you.</p>
<pre><code>npm install prettier-stylelint --save-dev
</code></pre><p>This tool <em>also</em> attempts to create a Prettier config based on the stylelint config.</p>
<p>Note that unlike prettier-eslint, you don’t have to install another package for its CLI since that is already included in it.</p>
<h4 id="heading-step-4"><strong>Step 4</strong></h4>
<p>Write scripts inside your <code>package.json</code> targeting the existing files in your codebase that you wish to run through prettier-eslint and prettier-stylelint.</p>
<pre><code><span class="hljs-string">"scripts"</span>: {
</code></pre><pre><code>  <span class="hljs-string">"fix-code"</span>: <span class="hljs-string">"prettier-eslint --write 'src/**/*.{js,jsx}' "</span>,
</code></pre><pre><code>  <span class="hljs-string">"fix-styles"</span>: <span class="hljs-string">"prettier-stylelint --write 'src/**/*.{css,scss}' "</span>
</code></pre><pre><code>}
</code></pre><p>As you can see, I am targeting all of my existing JS and JSX and all of my existing CSS and SCSS, respectively.</p>
<p>The <code>--write</code> flag writes the changes in-place for the file currently being formatted. So, be careful and <strong>make sure that all of your existing files are under source control and that there are no uncommited changed</strong>.</p>
<h4 id="heading-step-5"><strong>Step 5</strong></h4>
<p>Run the scripts!</p>
<pre><code>npm run fix-codenpm run fix-styles
</code></pre><p>Now, you can check-in all of these new changes as a single big commit (maybe even from a temporary git user, if you don’t wanna pollute your own git history.)</p>
<h3 id="heading-part-2-setting-up-vscode"><strong>Part 2: Setting up VSCode</strong></h3>
<p>Now that your existing codebase is formatted, its time to make sure that all the code being written henceforth is formatted automatically.</p>
<h4 id="heading-step-1-1"><strong>Step 1</strong></h4>
<p>Install the Prettier, ESLint, and stylelint extensions for VSCode:</p>
<p><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode"><strong>Prettier - Code formatter - Visual Studio Marketplace</strong></a><br><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode">_Extension for Visual Studio Code - VS Code plugin for prettier/prettier_marketplace.visualstudio.com</a><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint"><strong>ESLint - Visual Studio Marketplace</strong></a><br><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint">_Extension for Visual Studio Code - Integrates ESLint JavaScript into VS Code._marketplace.visualstudio.com</a><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=shinnn.stylelint"><strong>stylelint - Visual Studio Marketplace</strong></a><br><a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=shinnn.stylelint">_Extension for Visual Studio Code - Modern CSS/SCSS/Less linter_marketplace.visualstudio.com</a></p>
<h4 id="heading-step-2-1"><strong>Step 2</strong></h4>
<p>Configure a few VSCode settings:</p>
<p><code>"prettier.eslintIntegration": true</code> — tells Prettier to use prettier-eslint instead of Prettier</p>
<p><code>"prettier.stylelintIntegration": true</code> — tells Prettier to use prettier-stylelint instead of Prettier</p>
<p><code>"eslint.autoFixOnSave": false</code> — we don’t need ESLint to fix our code for us directly, since prettier-eslint will be running <code>eslint --fix</code> for us anyways.</p>
<p><code>"editor.formatOnSave": true</code> — runs Prettier with the above options on every file save, so you never have to manually invoke VSCode’s format command.</p>
<p>Additionally, you can check-in the above workplace settings to source control so its easier for other team members to set up their editors. You can do so by creating a <code>.vscode</code> folder at the root of your project and putting all of the above rules in a <code>settings.json</code> file.</p>
<p>Optionally, you can tell Prettier to ignore formatting certain patterns of files. To do this, just add a <code>.prettierignore</code> file to the root of your project specifying the paths to ignore. For instance:</p>
<pre><code>strings.jsonscripts<span class="hljs-comment">/*</span>
</code></pre><p><strong>And that’s it! Never worry about code styling again ?</strong></p>
<p>This article is by no means intended to be an exhaustive guide, but rather an introduction to what is possible with the amazing tools mentioned herein. I recommend opening up the official GitHub pages for each to learn more about how to utilise these tools more effectively for your specific workflow.</p>
<p>Please write a comment below for any help, suggestion, etc.</p>
<h4 id="heading-references"><em>References</em></h4>
<p>https://prettier.io/docs/en/<br>https://stylelint.io/user-guide/<br>https://eslint.org/<br>https://github.com/prettier/prettier-vscode<br>https://github.com/prettier/prettier-eslint<br>https://github.com/prettier/prettier-eslint-cli<br>https://github.com/hugomrdias/prettier-stylelint<br>https://www.youtube.com/watch?v=YIvjKId9m2c</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
