<?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[ Yarn - 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[ Yarn - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 28 Jul 2026 11:53:06 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/yarn/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Create an npm Library ]]>
                </title>
                <description>
                    <![CDATA[ In the world of JavaScript development, npm (Node Package Manager) has become an essential tool for managing dependencies and sharing reusable code. Whether you're building a simple website or a complex web application, npm libraries help streamline ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-an-npm-library/</link>
                <guid isPermaLink="false">67a627bfaf028c3f4ba71a05</guid>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Yarn ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Fri, 07 Feb 2025 15:33:19 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738941301640/7189d889-387d-4bd2-bf5c-2cbcbd17faad.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In the world of JavaScript development, <strong>npm</strong> (Node Package Manager) has become an essential tool for managing dependencies and sharing reusable code. Whether you're building a simple website or a complex web application, npm libraries help streamline development by providing pre-built solutions to common problems.</p>
<p>Another popular package manager is <strong>Yarn</strong>, which offers faster and more reliable dependency management while maintaining compatibility with the npm ecosystem.</p>
<p>In this article, we'll explore what npm libraries are, their benefits, and how they enhance the JavaScript and React ecosystem. We'll also go through a practical step-by-step guide on creating, publishing, and using your own npm library in a React project. We’ll also compare npm and Yarn, showing how you can use either of them effectively in your workflow.</p>
<p>By the end of this tutorial, you'll have a clear understanding of how to package and distribute your own code, making it reusable across multiple projects and even available to the wider developer community.</p>
<h2 id="heading-table-of-contents"><strong>Table of Contents</strong></h2>
<ol>
<li><p><a class="post-section-overview" href="#heading-what-is-npm">What is npm?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-npm-works">How npm works</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-role-of-packagejson">The role of the <code>package.json</code> file</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-key-npm-commands">Key npm Commands</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-why-use-npm-libraries">Why Use npm Libraries?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-code-reuse-and-modularization">Code reuse and modularization</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-simplified-dependency-management">Simplified dependency management</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-community-driven-ecosystem">Community-driven ecosystem</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-introducing-yarn-an-alternative-to-npm">Introducing Yarn: An Alternative to npm</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-yarn">What is Yarn?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-differences-between-npm-and-yarn">Differences between npm and Yarn</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-yarn-instead-of-npm">When to use Yarn instead of npm</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-create-your-own-npm-library">How to Create Your Own npm Library</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-setting-up-a-new-package">Setting up a new package</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-writing-modular-and-reusable-code">Writing modular and reusable code</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-adding-dependencies-and-peer-dependencies">Adding dependencies and peer dependencies</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-publish-your-library-to-npm">How to Publish Your Library to npm</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-creating-an-npm-account">Creating an npm account</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-configuring-packagejson-for-publishing">Configuring package.json for Publishing</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-publishing-the-package">Publishing the package</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-use-your-npm-library-in-a-react-project">How to Use Your npm Library in a React Project</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-installing-your-package">Installing your package</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-importing-and-using-the-library-in-a-react-component">Importing and using the package in a React component</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-handling-package-updates-and-versioning">Handling package updates and versioning</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-best-practices-for-npm-and-yarn-libraries">Best Practices for npm and Yarn Libraries</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-write-meaningful-documentation">Write Meaningful Documentation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-follow-semantic-versioning-semver">Follow Semantic Versioning (SemVer)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-keep-dependencies-up-to-date">Keep Dependencies Up to Date</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-write-unit-tests-for-your-library">Write Unit Tests for Your Library</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-ensure-cross-platform-compatibility">Ensure Cross-Platform Compatibility</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion &amp; Next Steps</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-recap-of-key-points">Recap of key points</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-additional-resources">Additional resources for npm and Yarn library development</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-encouragement-to-contribute-to-open-source">Encouragement to contribute to open-source</a></p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-what-is-npm"><strong>What is npm?</strong></h2>
<p>npm (Node Package Manager) is the default package manager for JavaScript and Node.js. It allows developers to install, share, and manage libraries or dependencies that make building applications easier and more efficient.</p>
<p>npm provides access to a vast ecosystem of open-source packages hosted on the <strong>npm registry</strong>, making it one of the largest software repositories in the world.</p>
<p>npm comes bundled with <strong>Node.js</strong>, meaning that once you install Node.js, you automatically have access to npm. You can check if npm is installed by running the following command in your terminal:</p>
<pre><code class="lang-python">npm -v
</code></pre>
<p>This command should return the version of npm installed on your system.</p>
<h3 id="heading-how-npm-works"><strong>How npm Works</strong></h3>
<p>npm operates through three key components:</p>
<ol>
<li><p><strong>The npm Registry</strong> – A public repository that hosts open-source JavaScript packages.</p>
</li>
<li><p><strong>The npm CLI (Command Line Interface)</strong> – A tool that allows developers to install, update, and manage packages from the command line.</p>
</li>
<li><p><strong>The package.json File</strong> – A metadata file that keeps track of dependencies, scripts, and project configurations.</p>
</li>
</ol>
<p>When you install a package using npm, it pulls the package from the registry and saves it in the <code>node_modules</code> folder within your project.</p>
<p>For example, to install <strong>Lodash</strong>, a popular utility library, you would run:</p>
<pre><code class="lang-python">npm install lodash
</code></pre>
<p>This will:</p>
<ul>
<li><p>Download the latest version of <code>lodash</code> from the npm registry</p>
</li>
<li><p>Add it to your <code>node_modules</code> folder</p>
</li>
<li><p>Update the <code>package.json</code> and <code>package-lock.json</code> files to reflect the new dependency</p>
</li>
</ul>
<h3 id="heading-the-role-of-packagejson"><strong>The Role of</strong> <code>package.json</code></h3>
<p>The <code>package.json</code> file is the heart of any npm project. It serves as a blueprint, containing information about the project, including:</p>
<ul>
<li><p><strong>Project metadata</strong> (name, version, description)</p>
</li>
<li><p><strong>Dependencies</strong> (external packages required for the project)</p>
</li>
<li><p><strong>Scripts</strong> (commands to automate tasks like starting a server or running tests)</p>
</li>
<li><p><strong>Versioning information</strong> (ensuring compatibility between different versions of dependencies)</p>
</li>
</ul>
<p>A typical <code>package.json</code> file looks like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-awesome-project"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A sample project demonstrating npm usage"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"node index.js"</span>,
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"echo \"No tests specified\" &amp;&amp; exit 0"</span>
  },
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"lodash"</span>: <span class="hljs-string">"^4.17.21"</span>
  },
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"eslint"</span>: <span class="hljs-string">"^8.0.0"</span>
  },
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Your Name"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"MIT"</span>
}
</code></pre>
<ul>
<li><p><code>dependencies</code> – Lists essential packages required for the application to function.</p>
</li>
<li><p><code>devDependencies</code> – Includes development-only dependencies (for example, testing and linting tools).</p>
</li>
<li><p><code>scripts</code> – Defines CLI commands for automating tasks.</p>
</li>
</ul>
<p>To install all dependencies listed in <code>package.json</code>, simply run:</p>
<pre><code class="lang-python">npm install
</code></pre>
<p>This ensures all required packages are downloaded and ready for use.</p>
<h3 id="heading-key-npm-commands"><strong>Key npm Commands</strong></h3>
<p>Here are some essential npm commands you’ll use frequently:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Command</td><td>Description</td></tr>
</thead>
<tbody>
<tr>
<td><code>npm init -y</code></td><td>Creates a default <code>package.json</code> file</td></tr>
<tr>
<td><code>npm install &lt;package-name&gt;</code></td><td>Installs a package and adds it to <code>dependencies</code></td></tr>
<tr>
<td><code>npm install &lt;package-name&gt; --save-dev</code></td><td>Installs a package and adds it to <code>devDependencies</code></td></tr>
<tr>
<td><code>npm uninstall &lt;package-name&gt;</code></td><td>Removes a package from the project</td></tr>
<tr>
<td><code>npm update</code></td><td>Updates all installed dependencies</td></tr>
<tr>
<td><code>npm outdated</code></td><td>Checks for outdated dependencies</td></tr>
<tr>
<td><code>npm run &lt;script-name&gt;</code></td><td>Runs a script defined in <code>package.json</code></td></tr>
</tbody>
</table>
</div><h2 id="heading-why-use-npm-libraries"><strong>Why Use npm Libraries?</strong></h2>
<p>As modern web development grows in complexity, using npm libraries has become essential for building scalable and maintainable applications. Instead of writing everything from scratch, you can leverage pre-built, tested, and optimized libraries to speed up development and ensure reliability.</p>
<p>In this section, we’ll explore the key advantages of using npm libraries and why they are crucial in JavaScript and React development.</p>
<h3 id="heading-code-reuse-and-modularization"><strong>Code Reuse and Modularization</strong></h3>
<p>One of the biggest benefits of npm libraries is <strong>code reuse</strong>. Instead of repeatedly writing the same functions or utilities in different projects, developers can:</p>
<ul>
<li><p>✅ Use existing open-source packages for common functionalities (for example, date formatting, HTTP requests, UI components).</p>
</li>
<li><p>✅ Create and publish their own reusable libraries to share across multiple projects.</p>
</li>
</ul>
<p>For example, instead of manually implementing a function to format dates, you can install a well-maintained package like date-fns:</p>
<pre><code class="lang-python">npm install date-fns
</code></pre>
<p>Then, you can use it in your project:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { format } <span class="hljs-keyword">from</span> <span class="hljs-string">"date-fns"</span>;

<span class="hljs-keyword">const</span> formattedDate = format(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(), <span class="hljs-string">"yyyy-MM-dd"</span>);
<span class="hljs-built_in">console</span>.log(formattedDate); <span class="hljs-comment">// Outputs: 2024-02-04 (or the current date)</span>
</code></pre>
<p>This modular approach saves time and ensures consistency across projects.</p>
<h3 id="heading-simplified-dependency-management"><strong>Simplified Dependency Management</strong></h3>
<p>npm makes it easy to manage dependencies in a project. Instead of manually downloading and maintaining different versions of external libraries, npm automates this process through the package.json and package-lock.json files.</p>
<p>Some key features include:</p>
<p>🔹 <strong>Automatic installation</strong> – Run <code>npm install</code>, and all dependencies are set up.<br>🔹 <strong>Version control</strong> – Specify package versions to avoid breaking changes.<br>🔹 <strong>Peer dependencies</strong> – Ensure compatibility between different libraries.</p>
<p>For example, here’s how npm helps manage dependency versions in <code>package.json</code>:</p>
<pre><code class="lang-json"><span class="hljs-string">"dependencies"</span>: {
  <span class="hljs-attr">"react"</span>: <span class="hljs-string">"^18.0.0"</span>,
  <span class="hljs-attr">"axios"</span>: <span class="hljs-string">"^1.5.0"</span>
}
</code></pre>
<ul>
<li><p><code>^18.0.0</code> – Allows minor updates but prevents major breaking changes.</p>
</li>
<li><p><code>axios</code> – Ensures HTTP requests are handled consistently across different projects.</p>
</li>
</ul>
<p>To update all dependencies safely, run:</p>
<pre><code class="lang-python">npm update
</code></pre>
<p>This ensures your project is always running on the latest stable versions.</p>
<h3 id="heading-community-driven-ecosystem"><strong>Community-Driven Ecosystem</strong></h3>
<p>npm has an active and growing community, meaning developers around the world contribute and maintain thousands of useful libraries. This results in:</p>
<p>🌎 <strong>Faster development</strong> – No need to reinvent the wheel.<br>🛠️ <strong>Well-tested solutions</strong> – Many libraries are battle-tested in production environments.<br>📚 <strong>Rich documentation</strong> – Most npm packages come with clear usage instructions and examples.</p>
<p>Popular npm libraries include:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Library</td><td>Purpose</td></tr>
</thead>
<tbody>
<tr>
<td><strong>React</strong> (<code>react</code>)</td><td>UI library for building web applications</td></tr>
<tr>
<td><strong>Axios</strong> (<code>axios</code>)</td><td>HTTP client for making API requests</td></tr>
<tr>
<td><strong>Lodash</strong> (<code>lodash</code>)</td><td>Utility functions for working with arrays, objects, and strings</td></tr>
<tr>
<td><strong>Express</strong> (<code>express</code>)</td><td>Web framework for building backend services</td></tr>
<tr>
<td><strong>Jest</strong> (<code>jest</code>)</td><td>JavaScript testing framework</td></tr>
</tbody>
</table>
</div><p>For example, using <strong>Axios</strong> to make an API request:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;

axios.get(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts/1"</span>)
  .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))
  .catch(<span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> <span class="hljs-built_in">console</span>.error(error));
</code></pre>
<p>This replaces the need for writing complex <code>fetch</code> requests with error handling manually.</p>
<h2 id="heading-introducing-yarn-an-alternative-to-npm"><strong>Introducing Yarn: An Alternative to npm</strong></h2>
<p>While <strong>npm</strong> is the default package manager for Node.js, another powerful alternative exists: <strong>Yarn</strong>. Developed by Facebook in 2016, Yarn was created to improve speed, security, and reliability in dependency management.</p>
<p>In this section, we’ll explore what Yarn is, how it differs from npm, and when you might prefer using Yarn over npm.</p>
<h3 id="heading-what-is-yarn"><strong>What is Yarn?</strong></h3>
<p>Yarn (<strong>Yet Another Resource Negotiator</strong>) is a package manager that works similarly to npm but with a focus on performance, security, and consistency. It offers:</p>
<p>🚀 <strong>Faster dependency installation</strong> thanks to parallel downloads<br>🔐 <strong>More secure package management</strong> using checksum verification<br>📦 <strong>Reliable dependency resolution</strong> with an offline cache</p>
<p>To check if you have Yarn installed, run:</p>
<pre><code class="lang-python">yarn -v
</code></pre>
<p>If you don’t have it yet, you can install it globally using npm:</p>
<pre><code class="lang-python">npm install --<span class="hljs-keyword">global</span> yarn
</code></pre>
<p>Once installed, you can use it just like npm to manage dependencies.</p>
<h3 id="heading-differences-between-npm-and-yarn"><strong>Differences Between npm and Yarn</strong></h3>
<p>Although npm and Yarn serve the same purpose, they have some key differences:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>npm</td><td>Yarn</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Speed</strong></td><td>Installs packages one at a time</td><td>Installs multiple packages in parallel (faster)</td></tr>
<tr>
<td><strong>Lock File</strong></td><td><code>package-lock.json</code></td><td><code>yarn.lock</code></td></tr>
<tr>
<td><strong>Offline Cache</strong></td><td>Not available (by default)</td><td>Can install packages from local cache</td></tr>
<tr>
<td><strong>Security</strong></td><td>Verifies package integrity but lacks checksum enforcement</td><td>Uses checksum verification for security</td></tr>
<tr>
<td><strong>Monorepo Support</strong></td><td>Supports workspaces but not optimized</td><td>Built-in support for monorepos with <code>workspaces</code></td></tr>
</tbody>
</table>
</div><h4 id="heading-performance-comparison"><strong>Performance Comparison</strong></h4>
<p>When installing dependencies, Yarn is often faster because it downloads packages in parallel, while npm installs them sequentially.</p>
<p>For example, to install all dependencies in a project:</p>
<pre><code class="lang-python"><span class="hljs-comment"># With npm</span>
npm install

<span class="hljs-comment"># With Yarn</span>
yarn install
</code></pre>
<p>Yarn can also install packages from a local cache, meaning it doesn't always need to fetch dependencies from the internet.</p>
<h4 id="heading-common-yarn-commands-vs-npm"><strong>Common Yarn Commands vs. npm</strong></h4>
<p>Many npm commands have an equivalent in Yarn:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Action</td><td>npm Command</td><td>Yarn Command</td></tr>
</thead>
<tbody>
<tr>
<td>Initialize a new project</td><td><code>npm init</code></td><td><code>yarn init</code></td></tr>
<tr>
<td>Install all dependencies</td><td><code>npm install</code></td><td><code>yarn install</code></td></tr>
<tr>
<td>Install a package</td><td><code>npm install package-name</code></td><td><code>yarn add package-name</code></td></tr>
<tr>
<td>Install a dev dependency</td><td><code>npm install package-name --save-dev</code></td><td><code>yarn add package-name --dev</code></td></tr>
<tr>
<td>Remove a package</td><td><code>npm uninstall package-name</code></td><td><code>yarn remove package-name</code></td></tr>
<tr>
<td>Update all packages</td><td><code>npm update</code></td><td><code>yarn upgrade</code></td></tr>
<tr>
<td>Run a script</td><td><code>npm run script-name</code></td><td><code>yarn script-name</code></td></tr>
</tbody>
</table>
</div><p>For example, installing <code>axios</code> using Yarn:</p>
<pre><code class="lang-python">yarn add axios
</code></pre>
<h3 id="heading-when-to-use-yarn-instead-of-npm"><strong>When to Use Yarn Instead of npm</strong></h3>
<p>Yarn is a great choice when:</p>
<ul>
<li><p><strong>You want faster installations</strong> – Yarn installs multiple packages in parallel, making it faster than npm.</p>
</li>
<li><p><strong>You need better dependency consistency</strong> – The <code>yarn.lock</code> file ensures that all developers use the same dependency versions.</p>
</li>
<li><p><strong>You're working with monorepos</strong> – Yarn’s built-in <strong>workspaces</strong> make it easier to manage multiple projects within the same repository.</p>
</li>
<li><p><strong>You want improved security</strong> – Yarn’s checksum verification prevents corrupted packages from being installed.</p>
</li>
</ul>
<p>Still, npm has improved significantly in recent years, especially with npm v7+, making it a viable choice for most projects.</p>
<h4 id="heading-switching-between-npm-and-yarn"><strong>Switching Between npm and Yarn</strong></h4>
<p>If your project was originally set up using npm but you want to switch to Yarn, you can:</p>
<p>1️⃣ <strong>Delete</strong> <code>node_modules</code> and <code>package-lock.json</code></p>
<pre><code class="lang-python">rm -rf node_modules package-lock.json
</code></pre>
<p>2️⃣ <strong>Run Yarn to install dependencies</strong></p>
<pre><code class="lang-python">yarn install
</code></pre>
<p>This will generate a yarn.lock file, ensuring all dependencies are managed by Yarn moving forward.</p>
<p>Both npm and Yarn are powerful tools for package management. Choosing between them depends on your project’s needs:</p>
<p>✔️ Use <strong>npm</strong> if you want the default, widely used package manager that works well with most projects.<br>✔️ Use <strong>Yarn</strong> if you need faster installs, better security, and monorepo support.</p>
<p>Ultimately, both tools allow you to <strong>install, manage, and publish</strong> JavaScript packages efficiently.</p>
<h2 id="heading-how-to-create-your-own-npm-library"><strong>How to Create Your Own npm Library</strong></h2>
<p>Creating your own npm library is a great way to <strong>share reusable code</strong>, contribute to the open-source community, or even streamline development across multiple projects. In this section, we’ll walk through the step-by-step process of setting up, coding, and preparing a library for publishing on npm.</p>
<h3 id="heading-setting-up-a-new-package"><strong>Setting Up a New Package</strong></h3>
<p>Before writing code, you need to set up an npm package. Follow these steps:</p>
<h4 id="heading-step-1-create-a-new-project-folder"><strong>Step 1: Create a New Project Folder</strong></h4>
<pre><code class="lang-python">mkdir my-awesome-library
cd my-awesome-library
</code></pre>
<h4 id="heading-step-2-initialize-npm"><strong>Step 2: Initialize npm</strong></h4>
<p>Run the following command to create a <code>package.json</code> file:</p>
<pre><code class="lang-python">npm init
</code></pre>
<p>You will be prompted to enter details such as:</p>
<ul>
<li><p>Package name</p>
</li>
<li><p>Version</p>
</li>
<li><p>Description</p>
</li>
<li><p>Entry point (default: <code>index.js</code>)</p>
</li>
<li><p>Author</p>
</li>
<li><p>License</p>
</li>
</ul>
<p>💡 To skip the prompts and create a default <code>package.json</code>, use:</p>
<pre><code class="lang-python">npm init -y
</code></pre>
<h3 id="heading-writing-modular-and-reusable-code"><strong>Writing Modular and Reusable Code</strong></h3>
<p>Now, let’s create a simple utility library that provides a function to format dates.</p>
<h4 id="heading-step-3-create-an-indexjs-file"><strong>Step 3: Create an</strong> <code>index.js</code> File</h4>
<p>Inside the project folder, create a file named <code>index.js</code> and add the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatDate</span>(<span class="hljs-params">date</span>) </span>{
  <span class="hljs-keyword">if</span> (!(date <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Date</span>)) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Invalid date"</span>);
  }
  <span class="hljs-keyword">return</span> date.toISOString().split(<span class="hljs-string">"T"</span>)[<span class="hljs-number">0</span>];
}

<span class="hljs-built_in">module</span>.exports = { formatDate };
</code></pre>
<h3 id="heading-adding-dependencies-and-peer-dependencies"><strong>Adding Dependencies and Peer Dependencies</strong></h3>
<p>Your library might depend on external packages. For example, let’s use date-fns for better date formatting.</p>
<p>To install it as a dependency, run:</p>
<pre><code class="lang-python">npm install date-fns
</code></pre>
<p>Then, modify <code>index.js</code> to use <code>date-fns</code>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { format } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"date-fns"</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">formatDate</span>(<span class="hljs-params">date</span>) </span>{
  <span class="hljs-keyword">if</span> (!(date <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Date</span>)) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Invalid date"</span>);
  }
  <span class="hljs-keyword">return</span> format(date, <span class="hljs-string">"yyyy-MM-dd"</span>);
}

<span class="hljs-built_in">module</span>.exports = { formatDate };
</code></pre>
<p>If you're creating a React-specific library, you should add React as a peer dependency:</p>
<pre><code class="lang-python">npm install react --save-peer
</code></pre>
<p>This ensures users of your library install React separately, preventing version conflicts.</p>
<p>Before publishing, you should test how your package works when installed as a dependency.</p>
<h4 id="heading-step-4-link-the-package-locally"><strong>Step 4: Link the Package Locally</strong></h4>
<p>Run the following command in your package folder:</p>
<pre><code class="lang-python">npm link
</code></pre>
<p>Then, in another project where you want to use your package, navigate to that project and run:</p>
<pre><code class="lang-python">npm link my-awesome-library
</code></pre>
<p>Now, you can import and use your function:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { formatDate } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"my-awesome-library"</span>);

<span class="hljs-built_in">console</span>.log(formatDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>())); <span class="hljs-comment">// Output: 2025-02-04 (or the current date)</span>
</code></pre>
<p>Once you're happy with your package, it's time to <strong>publish it on npm</strong>.</p>
<h2 id="heading-how-to-publish-your-library-to-npm"><strong>How to Publish Your Library to npm</strong></h2>
<p>Now that we’ve created our npm package, the next step is <strong>publishing it to the npm registry</strong> so others can install and use it. In this section, we’ll cover how to publish the package step by step.</p>
<h3 id="heading-creating-an-npm-account"><strong>Creating an npm Account</strong></h3>
<p>Before publishing, you need an npm account.</p>
<h4 id="heading-step-1-sign-up-for-npm"><strong>Step 1: Sign Up for npm</strong></h4>
<ol>
<li><p>Go to <a target="_blank" href="https://www.npmjs.com/signup">https://www.npmjs.com/signup</a> and create an account.</p>
</li>
<li><p>Verify your email address.</p>
</li>
</ol>
<h4 id="heading-step-2-log-in-to-npm-from-the-terminal"><strong>Step 2: Log in to npm from the Terminal</strong></h4>
<p>Run the following command in your terminal:</p>
<pre><code class="lang-python">npm login
</code></pre>
<p>You will be prompted to enter:</p>
<ul>
<li><p>Your npm username</p>
</li>
<li><p>Your password</p>
</li>
<li><p>Your email (associated with your npm account)</p>
</li>
</ul>
<p>If the login is successful, you’ll see a message:</p>
<pre><code class="lang-python">Logged <span class="hljs-keyword">in</span> <span class="hljs-keyword">as</span> your-username on https://registry.npmjs.org/
</code></pre>
<h3 id="heading-configuring-packagejson-for-publishing"><strong>Configuring package.json for Publishing</strong></h3>
<h4 id="heading-step-3-ensure-your-package-name-is-unique"><strong>Step 3: Ensure Your Package Name is Unique</strong></h4>
<p>Every npm package needs a unique name. Run the following command to check if your desired name is available:</p>
<pre><code class="lang-python">npm search my-awesome-library
</code></pre>
<p>If the name is already taken, you’ll need to modify <code>package.json</code> and change the <code>"name"</code> field.</p>
<h4 id="heading-step-4-add-metadata-and-keywords"><strong>Step 4: Add Metadata and Keywords</strong></h4>
<p>Open <code>package.json</code> and ensure it includes useful metadata:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-awesome-library"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A simple npm package for formatting dates"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"repository"</span>: {
    <span class="hljs-attr">"type"</span>: <span class="hljs-string">"git"</span>,
    <span class="hljs-attr">"url"</span>: <span class="hljs-string">"https://github.com/yourusername/my-awesome-library.git"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [<span class="hljs-string">"date"</span>, <span class="hljs-string">"formatter"</span>, <span class="hljs-string">"utility"</span>, <span class="hljs-string">"npm package"</span>],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Your Name &lt;your-email@example.com&gt;"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"MIT"</span>
}
</code></pre>
<p>🔹 <strong>repository</strong> – Useful if you plan to host the project on GitHub.<br>🔹 <strong>keywords</strong> – Helps people discover your package on npm.<br>🔹 <strong>license</strong> – Specifies how others can use your package (for example, MIT, GPL, and so on).</p>
<h3 id="heading-publishing-the-package"><strong>Publishing the Package</strong></h3>
<h4 id="heading-step-5-publish-your-package-to-npm"><strong>Step 5: Publish Your Package to npm</strong></h4>
<p>Run the following command inside your project folder:</p>
<pre><code class="lang-python">npm publish
</code></pre>
<p>If successful, you’ll see output similar to:</p>
<pre><code class="lang-python">+ my-awesome-library@<span class="hljs-number">1.0</span><span class="hljs-number">.0</span>
</code></pre>
<p>Your package is now available at:</p>
<p>📌 <a target="_blank" href="https://www.npmjs.com/package/my-awesome-library"><strong>https://www.npmjs.com/package/my-awesome-library</strong></a></p>
<h4 id="heading-step-6-making-changes-and-updating-the-package"><strong>Step 6: Making Changes and Updating the Package</strong></h4>
<p>If you want to release a new version, update the <code>version</code> field in <code>package.json</code>. npm follows Semantic Versioning (SemVer):</p>
<ul>
<li><p><strong>Patch:</strong> Bug fixes (1.0.0 → 1.0.1)</p>
</li>
<li><p><strong>Minor:</strong> New features, backward-compatible (1.0.0 → 1.1.0)</p>
</li>
<li><p><strong>Major:</strong> Breaking changes (1.0.0 → 2.0.0)</p>
</li>
</ul>
<p>Instead of manually updating <code>package.json</code>, use:</p>
<pre><code class="lang-python">npm version patch   <span class="hljs-comment"># 1.0.0 → 1.0.1</span>
npm version minor   <span class="hljs-comment"># 1.0.0 → 1.1.0</span>
npm version major   <span class="hljs-comment"># 1.0.0 → 2.0.0</span>
</code></pre>
<p>Then, publish the new version:</p>
<pre><code class="lang-python">npm publish
</code></pre>
<p>If you accidentally publish a package and need to remove it:</p>
<pre><code class="lang-python">npm unpublish my-awesome-library --force
</code></pre>
<p>⚠️ <strong>Note:</strong> You can only unpublish packages <strong>within 72 hours</strong> of publishing.</p>
<p>🎯 <strong>You’ve successfully published your own npm library!</strong> Now, other developers can install it using:</p>
<pre><code class="lang-python">npm install my-awesome-library
</code></pre>
<p>By following Semantic Versioning, writing clear documentation, and maintaining your package, you contribute to the open-source ecosystem and make your code reusable.</p>
<h2 id="heading-how-to-use-your-npm-library-in-a-react-project"><strong>How to Use Your npm Library in a React Project</strong></h2>
<p>Now that we’ve published our npm package, let’s see how to install, import, and use it inside a React project created with <strong>Vite</strong>. This section will guide you through the process using both npm and Yarn.</p>
<h3 id="heading-installing-your-package"><strong>Installing Your Package</strong></h3>
<h4 id="heading-step-1-create-a-new-react-project-with-vite-if-needed"><strong>Step 1: Create a New React Project with Vite (if needed)</strong></h4>
<p>If you don’t have an existing React project, create one using Vite:</p>
<h4 id="heading-using-npm"><strong>Using npm</strong></h4>
<pre><code class="lang-python">npm create vite@latest my-react-app --template react
cd my-react-app
npm install
</code></pre>
<h4 id="heading-using-yarn"><strong>Using Yarn</strong></h4>
<pre><code class="lang-python">yarn create vite@latest my-react-app --template react
cd my-react-app
yarn install
</code></pre>
<p>Once the installation is complete, you can start the development server:</p>
<pre><code class="lang-python">npm run dev
</code></pre>
<p>or</p>
<pre><code class="lang-python">yarn dev
</code></pre>
<h4 id="heading-step-2-install-your-npm-package"><strong>Step 2: Install Your npm Package</strong></h4>
<p>Now, install the npm library we created earlier (<code>my-awesome-library</code>).</p>
<h4 id="heading-using-npm-1"><strong>Using npm</strong></h4>
<pre><code class="lang-python">npm install my-awesome-library
</code></pre>
<h4 id="heading-using-yarn-1"><strong>Using Yarn</strong></h4>
<pre><code class="lang-python">yarn add my-awesome-library
</code></pre>
<h3 id="heading-importing-and-using-the-library-in-a-react-component"><strong>Importing and Using the Library in a React Component</strong></h3>
<p>Once installed, you can use the library inside a React component.</p>
<p>Open <code>src/App.jsx</code> and modify it as follows:</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> { formatDate } <span class="hljs-keyword">from</span> <span class="hljs-string">"my-awesome-library"</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> today = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Formatted Date<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{formatDate(today)}<span class="hljs-tag">&lt;/<span class="hljs-name">p</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>Now, run your Vite React app:</p>
<pre><code class="lang-python">npm run dev
</code></pre>
<p>Or with Yarn:</p>
<pre><code class="lang-python">yarn dev
</code></pre>
<p>This will display a formatted date on the webpage, confirming that our library is working!</p>
<h3 id="heading-handling-package-updates-and-versioning"><strong>Handling Package Updates and Versioning</strong></h3>
<p>To update your npm package in your project:</p>
<h4 id="heading-using-npm-2"><strong>Using npm</strong></h4>
<pre><code class="lang-python">npm update my-awesome-library
</code></pre>
<h4 id="heading-using-yarn-2"><strong>Using Yarn</strong></h4>
<pre><code class="lang-python">yarn upgrade my-awesome-library
</code></pre>
<p>If you want to check outdated dependencies:</p>
<pre><code class="lang-python">npm outdated
</code></pre>
<p>or</p>
<pre><code class="lang-python">yarn outdated
</code></pre>
<h3 id="heading-using-a-local-version-of-your-package-in-development"><strong>Using a Local Version of Your Package in Development</strong></h3>
<p>If you’re still making changes to your npm package and want to test it in your React project <strong>before publishing</strong>, you can use <code>npm link</code> or <code>yarn link</code>.</p>
<h4 id="heading-step-1-link-your-package-locally"><strong>Step 1: Link Your Package Locally</strong></h4>
<p>Go to your package’s project folder:</p>
<pre><code class="lang-python">cd ~/path-to-my-awesome-library
npm link
</code></pre>
<p>or</p>
<pre><code class="lang-python">yarn link
</code></pre>
<h4 id="heading-step-2-use-it-in-your-react-project"><strong>Step 2: Use It in Your React Project</strong></h4>
<p>Navigate to your React app and link the package:</p>
<pre><code class="lang-python">cd ~/path-to-my-react-app
npm link my-awesome-library
</code></pre>
<p>or</p>
<pre><code class="lang-python">yarn link my-awesome-library
</code></pre>
<p>Now, when you import and use <code>my-awesome-library</code>, it will use the local version instead of the published one.</p>
<h3 id="heading-publishing-an-update-to-your-package"><strong>Publishing an Update to Your Package</strong></h3>
<p>If you’ve made changes to your package and want to publish a new version:</p>
<p>1️⃣ <strong>Update the version number</strong> in <code>package.json</code> (use <code>npm version patch</code> for small updates).<br>2️⃣ <strong>Run</strong> <code>npm publish</code> to upload the new version.<br>3️⃣ <strong>Run</strong> <code>npm update my-awesome-library</code> in your React project to get the latest version.</p>
<h3 id="heading-final-thoughts-on-using-npm-libraries-in-react-vite-edition"><strong>Final Thoughts on Using npm Libraries in React (Vite Edition)</strong></h3>
<p>By now, you should have a fully functional npm package and know how to install, use, and update it in a React project using Vite.</p>
<p>✔️ Vite is faster than Create React App and provides better performance for development.<br>✔️ npm and Yarn make dependency management easy.<br>✔️ <code>npm link</code> allows local testing before publishing.<br>✔️ Keeping dependencies updated ensures stability.</p>
<p>This workflow is essential for developers looking to create, maintain, and distribute reusable React components or JavaScript utilities.</p>
<h2 id="heading-best-practices-for-npm-and-yarn-libraries"><strong>Best Practices for npm and Yarn Libraries</strong></h2>
<p>Now that you've created, published, and used your own npm package, it's essential to follow best practices to ensure your package is reliable, maintainable, and easy to use. This section will cover key principles and techniques to make your npm library as professional as possible.</p>
<h3 id="heading-write-meaningful-documentation"><strong>Write Meaningful Documentation</strong></h3>
<p>A well-documented library helps other developers understand how to use it effectively.</p>
<h4 id="heading-what-to-include-in-your-documentation"><strong>What to Include in Your Documentation</strong></h4>
<p>📌 Installation instructions<br>📌 Usage examples<br>📌 API reference (functions, parameters, return values)<br>📌 Versioning and update history<br>📌 Contributions guide (if open-source)</p>
<p>For example, a simple <a target="_blank" href="http://README.md"><code>README.md</code></a> file for my-awesome-library:</p>
<pre><code class="lang-python"><span class="hljs-comment"># my-awesome-library</span>

A simple npm package <span class="hljs-keyword">for</span> formatting dates.

<span class="hljs-comment">## Installation</span>

<span class="hljs-comment">### Using npm</span>
```sh
npm install my-awesome-library
</code></pre>
<h4 id="heading-using-yarn-3">Using Yarn</h4>
<pre><code class="lang-python">yarn add my-awesome-library
</code></pre>
<h4 id="heading-usage">Usage</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { formatDate } <span class="hljs-keyword">from</span> <span class="hljs-string">"my-awesome-library"</span>;

<span class="hljs-built_in">console</span>.log(formatDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>())); <span class="hljs-comment">// Outputs: 2025-02-04</span>
</code></pre>
<h3 id="heading-follow-semantic-versioning-semver"><strong>Follow Semantic Versioning (SemVer)</strong></h3>
<p>Versioning helps maintain compatibility and informs users of changes. npm follows Semantic Versioning (SemVer):</p>
<p>MAJOR.MINOR.PATCH</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Change Type</td><td>Example</td><td>Meaning</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Patch</strong></td><td><code>1.0.0 → 1.0.1</code></td><td>Bug fixes, no breaking changes</td></tr>
<tr>
<td><strong>Minor</strong></td><td><code>1.0.0 → 1.1.0</code></td><td>New features, no breaking changes</td></tr>
<tr>
<td><strong>Major</strong></td><td><code>1.0.0 → 2.0.0</code></td><td>Breaking changes</td></tr>
</tbody>
</table>
</div><p>💡 To bump versions automatically, use:</p>
<pre><code class="lang-javascript"><span class="hljs-string">``</span><span class="hljs-string">`sh
npm version patch   # Small bug fix
npm version minor   # New feature added
npm version major   # Breaking changes</span>
</code></pre>
<p>Then, publish the new version:</p>
<pre><code class="lang-javascript">npm publish
</code></pre>
<p>👉 Use proper versioning to prevent breaking projects that depend on your library.</p>
<h3 id="heading-keep-dependencies-up-to-date"><strong>Keep Dependencies Up to Date</strong></h3>
<p>Regularly updating dependencies improves security, performance, and compatibility.</p>
<h4 id="heading-check-for-outdated-dependencies"><strong>Check for outdated dependencies:</strong></h4>
<pre><code class="lang-javascript">npm outdated
</code></pre>
<p>or</p>
<pre><code class="lang-javascript">yarn outdated
</code></pre>
<h4 id="heading-update-dependencies"><strong>Update dependencies:</strong></h4>
<pre><code class="lang-javascript">npm update
</code></pre>
<p>or</p>
<pre><code class="lang-javascript">yarn upgrade
</code></pre>
<h3 id="heading-write-unit-tests-for-your-library"><strong>Write Unit Tests for Your Library</strong></h3>
<p>Testing ensures your package works correctly before publishing updates.</p>
<h4 id="heading-install-a-testing-framework-jest"><strong>Install a Testing Framework (Jest)</strong></h4>
<pre><code class="lang-javascript">npm install --save-dev jest
</code></pre>
<h4 id="heading-create-a-test-file-indextestjs"><strong>Create a Test File (</strong><code>index.test.js</code>)</h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { formatDate } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./index"</span>);

test(<span class="hljs-string">"formats a date correctly"</span>, <span class="hljs-function">() =&gt;</span> {
  expect(formatDate(<span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">"2025-02-04"</span>))).toBe(<span class="hljs-string">"2025-02-04"</span>);
});

test(<span class="hljs-string">"throws an error if input is not a date"</span>, <span class="hljs-function">() =&gt;</span> {
  expect(<span class="hljs-function">() =&gt;</span> formatDate(<span class="hljs-string">"not a date"</span>)).toThrow(<span class="hljs-string">"Invalid date"</span>);
});
</code></pre>
<h4 id="heading-run-tests"><strong>Run Tests</strong></h4>
<pre><code class="lang-javascript">shCopyEditnpm test
</code></pre>
<p>👉 You can use CI/CD (for example, GitHub Actions) to run tests automatically on every push.</p>
<h3 id="heading-using-cicd-for-automated-publishing"><strong>Using CI/CD for Automated Publishing</strong></h3>
<h4 id="heading-automate-publishing-with-github-actions"><strong>Automate Publishing with GitHub Actions</strong></h4>
<p>Create a <code>.github/workflows/publish.yml</code> file:</p>
<pre><code class="lang-javascript">ymlCopyEditname: Publish to npm
<span class="hljs-attr">on</span>:
  push:
    branches:
      - main

<span class="hljs-attr">jobs</span>:
  publish:
    runs-on: ubuntu-latest
    <span class="hljs-attr">steps</span>:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        <span class="hljs-attr">with</span>:
          node-version: <span class="hljs-number">18</span>
          registry-url: <span class="hljs-string">"https://registry.npmjs.org/"</span>
      - run: npm install
      - run: npm test
      - run: npm publish
        <span class="hljs-attr">env</span>:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
</code></pre>
<p>1️⃣ <strong>Create an npm token</strong>:<br>Run:</p>
<pre><code class="lang-javascript">shCopyEditnpm token create
</code></pre>
<p>Copy the token and add it to GitHub Secrets (<code>NPM_TOKEN</code>).</p>
<p>2️⃣ <strong>Push code to GitHub</strong> → Auto-publish on npm!</p>
<p>👉 Automating publishing prevents human errors and ensures quality control.</p>
<h3 id="heading-ensure-cross-platform-compatibility"><strong>Ensure Cross-Platform Compatibility</strong></h3>
<ul>
<li><p>Use <strong>ES modules (</strong><code>import/export</code>) for modern compatibility.</p>
</li>
<li><p>Include <strong>CommonJS (</strong><code>require/module.exports</code>) support for older environments.</p>
</li>
<li><p>Test with different <strong>Node.js versions</strong> using CI/CD.</p>
</li>
</ul>
<p>Example <code>package.json</code> for dual compatibility:</p>
<pre><code class="lang-javascript">jsonCopyEdit<span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span>,
<span class="hljs-string">"main"</span>: <span class="hljs-string">"index.cjs"</span>,
<span class="hljs-string">"exports"</span>: {
  <span class="hljs-string">"import"</span>: <span class="hljs-string">"./index.mjs"</span>,
  <span class="hljs-string">"require"</span>: <span class="hljs-string">"./index.cjs"</span>
}
</code></pre>
<p>👉 This ensures your package works everywhere (Node.js, React, Next.js, and so on).</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Congratulations! 🎉 You’ve successfully learned how to create, publish, and use your own npm package, while also understanding the benefits of both <strong>npm</strong> and <strong>Yarn</strong> for package management.</p>
<p>Throughout this guide, we covered:</p>
<p>✔️ What npm is and why it’s important<br>✔️ How to use npm and Yarn to manage dependencies<br>✔️ How to create a reusable npm package<br>✔️ How to publish and update your package on npm<br>✔️ How to integrate your package into a React project with Vite<br>✔️ Best practices for writing, testing, and maintaining your library</p>
<p>By following these steps, you've taken an important step toward open-source development and modular programming, making your code reusable for both yourself and the developer community.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Package Manager – Complete Guide to NPM and Yarn ]]>
                </title>
                <description>
                    <![CDATA[ A package manager is a tool developers use to automate finding, downloading, installing, configuring, upgrading, and removing a system's packages. This article will show you all you need to get started with package managers like NPM and Yarn. But why... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-package-manager-npm-and-yarn/</link>
                <guid isPermaLink="false">66ba0dfd7fb82b484b253a2b</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Yarn ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Tue, 05 Apr 2022 00:08:08 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/package-manager-npm-and-yarn-explained-curology-pDsmoI5j3B8-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A <strong>package manager</strong> is a tool developers use to automate finding, downloading, installing, configuring, upgrading, and removing a system's packages.</p>
<p>This article will show you all you need to get started with package managers like NPM and Yarn.</p>
<p>But why exactly do we need a package manager in our development workflow? Let's find out.</p>
<h2 id="heading-why-do-you-need-a-package-manager">Why Do You Need a Package Manager?</h2>
<p>Suppose there were no package managers. In that case, you would have to do the following manually:</p>
<ul>
<li>Find all the correct packages for your project</li>
<li>Verify that the packages don't have any known vulnerabilities</li>
<li>Download the packages</li>
<li>Install them at the appropriate location</li>
<li>Keep track of new updates for all your packages</li>
<li>Upgrade each package whenever there is a new release</li>
<li>Remove the packages you no longer need</li>
</ul>
<p>Manually managing tens or hundreds of packages is a tiresome and time-consuming endeavor.</p>
<p>Therefore, package managers—such as <a target="_blank" href="https://www.npmjs.com/">NPM</a>, <a target="_blank" href="https://pnpm.io/">pNPM</a>, <a target="_blank" href="https://bower.io/">Bower</a>, and <a target="_blank" href="https://yarnpkg.com/">Yarn</a>—help automate and eliminate the tedious process of managing all your packages manually.</p>
<p>Keep in mind that a package manager is not the same as a package registry. So, let's find out the main difference.</p>
<h2 id="heading-package-manager-vs-package-registry-whats-the-difference">Package Manager vs. Package Registry – What's the Difference?</h2>
<p>A <strong>package manager</strong> is a tool developers use to automatically find, download, install, configure, upgrade, and uninstall a computer's packages.</p>
<p>NPM (Node Package Manager) and Yarn (Yet Another Resource Negotiator) are two popularly used package managers.</p>
<p>A <strong>package registry</strong> is a database (storage) for thousands of packages (libraries, plugins, frameworks, or tools).</p>
<p>In other words, a package registry is the place packages get published to and installed from.</p>
<p><a target="_blank" href="https://www.npmjs.com/">NPM registry</a> and <a target="_blank" href="https://github.com/features/packages">GitHub Packages</a> are two popularly used package registries.</p>
<p>So, now that we know what a package manager is and why it is needed, we can discuss how to use the two popular ones—NPM and Yarn.</p>
<p>Note that there are numerous NPM vs. Yarn debates out there – so we will avoid them here because the best package manager is the one that works best for you.</p>
<p>Therefore, this article will show you how NPM and Yarn work rather than tell you which package manager is best. It is then up to you to decide which you prefer.</p>
<p>Alternatively, you can choose to use NPM for a specific project and Yarn for another—depending on which manager you believe is best suited for the job.</p>
<p>So, without any further ado, let's begin by learning how to install the two managers.</p>
<h2 id="heading-how-to-install-node-package-manager-npm">How to Install Node Package Manager (NPM)</h2>
<p>NPM gets installed automatically while installing Node.</p>
<p>Therefore, to get NPM installed on your system, go to the <a target="_blank" href="https://nodejs.org/en/">NodeJS</a> website and get Node's <a target="_blank" href="https://tamalweb.com/which-nodejs-version">latest LTS or the current version</a>.</p>
<h2 id="heading-how-to-install-yarn">How to Install Yarn</h2>
<p>It is best to install Yarn through NPM. So, first, install NPM from the <a target="_blank" href="https://nodejs.org/en/">Node.js</a> website.</p>
<p>Once you've installed NPM, proceed to install Yarn like so:</p>
<pre><code class="lang-bash">npm install -g yarn
</code></pre>
<h2 id="heading-how-to-check-the-installed-node-version">How to Check the Installed Node Version</h2>
<p>To check the Node.js version installed on your system, run:</p>
<pre><code class="lang-bash">node -v
</code></pre>
<p>The <code>-v</code> flag in the snippet above is a shorthand for <code>--version</code>.</p>
<h2 id="heading-how-to-check-the-installed-npm-version">How to Check the Installed NPM Version</h2>
<p>To check the NPM version installed on your system, run:</p>
<pre><code class="lang-bash">npm -v
</code></pre>
<h2 id="heading-how-to-check-the-installed-yarn-version">How to Check the Installed Yarn Version</h2>
<p>To check the Yarn version installed on your system, run:</p>
<pre><code class="lang-bash">yarn -v
</code></pre>
<h2 id="heading-how-to-upgrade-node-package-manager">How to Upgrade Node Package Manager</h2>
<p>Update to the latest NPM version by running:</p>
<pre><code class="lang-bash">npm install npm@latest -g
</code></pre>
<h2 id="heading-how-to-upgrade-nodejs">How to Upgrade NodeJS</h2>
<p>Suppose you wish to upgrade your Node.js installation. In that case, you have two options:</p>
<h3 id="heading-option-1-upgrade-via-the-nodejs-website">Option 1: Upgrade via the NodeJS website</h3>
<p>One way to upgrade your NodeJS installation is to manually download and install the latest version from the <a target="_blank" href="https://nodejs.org/en/">Node.js website</a>.</p>
<h3 id="heading-option-2-upgrade-via-a-version-management-tool">Option 2: Upgrade via a version management tool</h3>
<p>Another way to upgrade your NodeJS installation is to use a <a target="_blank" href="https://nodejs.org/en/download/package-manager/">version manager</a> such as <a target="_blank" href="https://github.com/nvm-sh/nvm">NVM</a>, <a target="_blank" href="https://github.com/tj/n">n</a>, or <a target="_blank" href="https://github.com/jasongin/nvs">nvs</a>.</p>
<h2 id="heading-how-to-upgrade-yarn">How to Upgrade Yarn</h2>
<p>Update to the latest Yarn version by running:</p>
<pre><code class="lang-bash">yarn <span class="hljs-built_in">set</span> version latest
</code></pre>
<p>So, now that we have NPM (or Yarn) on our computer, we can start using the installed manager to find, install, configure, and remove our project's packages.</p>
<p>But what exactly is a package? Let's find out.</p>
<h2 id="heading-what-exactly-is-a-package">What Exactly Is a Package?</h2>
<p>A <strong>package</strong> is a <a target="_blank" href="https://www.codesweetly.com/git-basic-introduction/#h-working-directory">directory</a> (or project) that has a <code>package.json</code> file used to record information about it.</p>
<p><strong>Note:</strong> You can only publish packages (a project described by a <code>package.json</code> file) to the <a target="_blank" href="https://docs.npmjs.com/cli/v6/using-npm/registry">NPM registry</a>.</p>
<h2 id="heading-how-to-install-packages">How to Install Packages</h2>
<p>There are two ways to install a package: locally or globally.</p>
<h3 id="heading-local-package-installation">Local package installation</h3>
<p>A locally installed package is one that you can use only in the project in which you've installed it.</p>
<p>To install a package locally, do the following:</p>
<ol>
<li>Navigate to the <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary/#h-root-directory">root directory</a> of your project from the command line.</li>
<li>Install your package using the NPM or Yarn installation command below (depending on the package manager you've chosen to use for your project).</li>
</ol>
<p><strong>Note:</strong> You must have Node and NPM installed on your system for the NPM (and Yarn) installation commands below to work. You can get both by installing the latest LTS or the current version from the Node.js website.</p>
<h4 id="heading-npm-installation-command">NPM installation command</h4>
<pre><code class="lang-bash">npm install package-name --save
</code></pre>
<p>Note that the <code>--save</code> command above instructs NPM to save <code>package-name</code> in the <code>package.json</code> file as one of the packages on which the project depends.</p>
<p>Suppose you wish to install an exact version of a package. In such a case, add a <code>@[version-number]</code> after the package's name like so:</p>
<pre><code class="lang-bash">npm install package-name@4.14.1 --save
</code></pre>
<p>Alternatively, if the package you are installing is for development and testing purposes, use:</p>
<pre><code class="lang-bash">npm install package-name --save-dev
</code></pre>
<p>The commands above will cause NPM to download three items into your project's root directory: a <code>node_modules</code> folder, a <code>package.json</code> file, and a <code>package-lock.json</code> file. We will discuss these items in detail later on in this article.</p>
<h4 id="heading-yarn-installation-command">Yarn installation command</h4>
<pre><code class="lang-bash">yarn add package-name
</code></pre>
<p>Suppose you wish to install an exact version of a package. In such a case, add a <code>@[version-number]</code> after the package's name like so:</p>
<pre><code class="lang-bash">yarn add package-name@4.14.1
</code></pre>
<p>Alternatively, if the package you are installing is for development and testing purposes, use:</p>
<pre><code class="lang-bash">yarn add package-name --dev
</code></pre>
<p>The commands above will cause Yarn to download three items into your project's root directory: a <code>node_modules</code> folder, a <code>package.json</code> file, and a <code>yarn.lock</code> file. We will discuss these items in detail later on in this article.</p>
<p>So, now that we know how to install a package locally, we can discuss the global package installation.</p>
<h3 id="heading-global-package-installation">Global package installation</h3>
<p>A globally installed package is a package that you can use anywhere on your system.</p>
<p>To install a package globally, run the code below on your terminal:</p>
<pre><code class="lang-bash">npm install package-name -g
</code></pre>
<p>Alternatively, you can use Yarn like so:</p>
<pre><code class="lang-bash">yarn global add package-name
</code></pre>
<p>Note that you can run the commands above from any location on your system.</p>
<h3 id="heading-local-vs-global-package-installation">Local vs. global package installation</h3>
<p>Generally, it is better to install a package locally. Below are some of the differences between a local and global installation.</p>
<h4 id="heading-difference-1-installation-location">Difference 1: Installation location</h4>
<p>A locally installed package gets installed in the directory where you executed the <code>npm install package-name</code> (or <code>yarn add package-name</code>) command.</p>
<p>Specifically, you will find a project's locally installed packages in its <code>node_module</code> directory.</p>
<p>In contrast, a globally installed package gets installed in a single location on your system. The exact location depends on your system's configuration.</p>
<h4 id="heading-difference-2-package-versions">Difference 2: Package versions</h4>
<p>Suppose you installed your package locally. Then, you can use different versions of the same package for multiple app development.</p>
<p>However, you are forced to use the same package version for all your apps when you install globally.</p>
<h4 id="heading-difference-3-updates">Difference 3: Updates</h4>
<p>A local installation allows you to choose the project's packages you wish to upgrade to the latest version. This makes it easier to manage upgrades that break compatibility with other packages.</p>
<p>However, upgrading a globally installed package updates the package for all projects—which can cause maintenance nightmares if the upgrade breaks compatibility with other packages.</p>
<h4 id="heading-difference-4-usage-recommendation">Difference 4: Usage recommendation</h4>
<p>Global installation is best for packages you intend to use only on your command line—especially when they provide executable commands reusable across projects.</p>
<p>However, local installation is best for packages you intend to use in your program—through the <code>import</code> statement or <code>require()</code> function.</p>
<h4 id="heading-difference-5-examples">Difference 5: Examples</h4>
<p><a target="_blank" href="https://www.npmjs.com/">NPM</a>, <a target="_blank" href="https://reactnative.dev/docs/environment-setup">React Native CLI</a>, <a target="_blank" href="https://www.gatsbyjs.com/docs/reference/gatsby-cli/">Gatsby CLI</a>, <a target="_blank" href="https://gruntjs.com/getting-started">Grunt CLI</a>, and <a target="_blank" href="https://cli.vuejs.org/">Vue CLI</a> are well-known examples of global packages.</p>
<p>Common examples of local packages are <a target="_blank" href="https://webpack.js.org/">Webpack</a>, <a target="_blank" href="https://lodash.com/">Lodash</a>, <a target="_blank" href="https://jestjs.io/">Jest</a>, and <a target="_blank" href="https://momentjs.com/">MomentJS</a>.</p>
<p><strong>Note:</strong></p>
<ul>
<li>You can <a target="_blank" href="https://nodejs.org/en/blog/npm/npm-1-0-global-vs-local-installation/#when-you-can-t-choose">do both local and global installation</a> of packages you intend to use both on the command line and in your project. Typical examples of such packages are <a target="_blank" href="https://expressjs.com/">ExpressJS</a> and <a target="_blank" href="https://coffeescript.org/">CoffeeScript</a>.</li>
<li>Your package manager does not execute an installed package. NPM (and Yarn) only install packages to the <code>node_modules</code> directory. And if you had specified the <code>--save</code> command, your manager would add details about the package to the <code>package.json</code> file.</li>
<li>To execute (run) any <a target="_blank" href="https://helpdeskgeek.com/how-to/what-is-an-executable-file-how-to-create-one/">executable</a> package, you must explicitly do so yourself. We will discuss how in a later section of this article.</li>
</ul>
<p>But what exactly are the <code>node_modules</code> folder, <code>package.json</code> file, <code>package-lock.json</code> file, and <code>yarn.lock</code> file? Let's find out.</p>
<h2 id="heading-what-is-a-nodemodules-folder">What Is a <code>node_modules</code> Folder?</h2>
<p>The <strong>node_modules</strong> directory is the folder where NPM places all the packages it downloads locally for your project.</p>
<h2 id="heading-what-is-a-packagejson-file">What Is a <code>package.json</code> File?</h2>
<p>A <strong>package.json</strong> file is a JSON document that package managers—like NPM and Yarn—use to store information about a specific project.</p>
<p>In other words, a <code>package.json</code> file is a project's metadata file.</p>
<h3 id="heading-advantages-of-a-packagejson-file">Advantages of a <code>package.json</code> File</h3>
<p>A <code>package.json</code> file:</p>
<ul>
<li>makes it possible to publish your project to the NPM registry</li>
<li>makes it easy for others to manage and install your package</li>
<li>helps NPM manage a <a target="_blank" href="https://www.codesweetly.com/javascript-modules-tutorial/">module</a>'s dependencies easily</li>
<li>makes your package reproducible and shareable with other developers</li>
</ul>
<h3 id="heading-how-to-create-a-packagejson-file">How to Create a <code>package.json</code> File</h3>
<p>Go to your project's root directory and initialize the creation of a <code>package.json</code> file by running:</p>
<pre><code class="lang-bash">npm init
</code></pre>
<p>Or, if your package manager is Yarn, run:</p>
<pre><code class="lang-bash">yarn init
</code></pre>
<p>Once you've executed the initialization command above, your package manager will walk you through creating the <code>package.json</code> file by asking a few questions about your project.</p>
<p>If you wish to skip the questionnaire, you can create a default <code>package.json</code> file. Let's see how.</p>
<h3 id="heading-how-to-create-a-default-packagejson-file">How to Create a Default <code>package.json</code> File</h3>
<p>Suppose you prefer to skip the questionnaire prompted by the <code>npm init</code> (or <code>yarn init</code>) command. In such a case, go to your project's <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary/#h-root-directory">root directory</a> and run:</p>
<pre><code class="lang-bash">npm init -y
</code></pre>
<p>Or, if your package manager is Yarn, run:</p>
<pre><code class="lang-bash">yarn init -y
</code></pre>
<p>The command above will use <a target="_blank" href="https://docs.npmjs.com/creating-a-package-json-file#default-values-extracted-from-the-current-directory">default values extracted from the current directory</a> to create your project's <code>package.json</code> file.</p>
<p><strong>Note:</strong> The <code>-y</code> flag is a shorthand for <code>--yes</code>.</p>
<p>Once your package manager finishes its initialization process, your project's <code>package.json</code> file will contain an object with a set of properties.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"codesweetly-project"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>
}
</code></pre>
<p>You can see that the <code>package.json</code> file above contains the <code>name</code>, <code>version</code>, and <code>main</code> fields. Let's learn more about these properties below.</p>
<h3 id="heading-the-packagejsons-fields">The <code>package.json</code>'s Fields</h3>
<p>The <code>package.json</code>'s properties make your project usable to package managers and end-users.</p>
<p>Suppose you wish to publish your package to the NPM registry. In that case, your <code>package.json</code> file must have the <code>"name"</code> and <code>"version"</code> fields.</p>
<p>However, if you do not intend to publish your package, in that case, all fields—including the <code>"name"</code> and <code>"version"</code> properties—are optional.</p>
<p>Let's learn more about the commonly used fields in a <code>package.json</code> file.</p>
<h4 id="heading-name">name</h4>
<p>The <code>"name"</code> field is a property used to record a project's name.</p>
<p>The <code>"name"</code> property's value must be:</p>
<ul>
<li>a single word</li>
<li>lowercase lettering</li>
<li>and less than or equal to 214 characters</li>
</ul>
<p>Note that you can join words together with hyphens and underscores.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"code_sweetly-project"</span>
}
</code></pre>
<h4 id="heading-version">version</h4>
<p>The <code>"version"</code> field indicates a project's current version number.</p>
<p>The <code>"version"</code> property must be in the form of a <code>major.minor.patch</code> format. It must also follow the <a target="_blank" href="https://docs.npmjs.com/about-semantic-versioning">semantic versioning guidelines</a>.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>
}
</code></pre>
<h4 id="heading-description">description</h4>
<p>The <code>"description"</code> field is a property containing a brief description of a project's purpose.</p>
<p>NPM recommends having a <code>"description"</code> property to make your package easier to find on the NPM website.</p>
<p>Your description will be one of the things that's shown when people run the <code>npm search</code> command.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A brief description about this package (project)"</span>
}
</code></pre>
<h4 id="heading-main">main</h4>
<p>The <code>"main"</code> field indicates a project's <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary/#entry-point">entry point</a>.</p>
<p>In other words, when someone runs the <code>require()</code> function, Node will resolve the invocation to <code>require(&lt;package.json:main&gt;)</code>.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"./src/index.js"</span>
}
</code></pre>
<h4 id="heading-private">private</h4>
<p>The <code>"private"</code> field lets package managers know whether they should publish your project to the NPM registry.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"private"</span>: <span class="hljs-literal">true</span>
}
</code></pre>
<p>If you set your package.json's <code>"private"</code> property to <code>true</code>, package managers will not publish your project.</p>
<p>Therefore, setting the property is an excellent way to prevent accidental publication of your package.</p>
<h4 id="heading-scripts">scripts</h4>
<p>The <code>"scripts"</code> field defines the script commands you want to run at various times in your project's lifecycle.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"jest"</span>,
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"webpack --mode development"</span>,
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"webpack --mode production"</span>,
    <span class="hljs-attr">"predeploy"</span>: <span class="hljs-string">"npm run build"</span>,
    <span class="hljs-attr">"deploy"</span>: <span class="hljs-string">"gh-pages -d build"</span> 
  }
}
</code></pre>
<p>The <code>"scripts"</code> field above contains five properties whose values are the commands we want our package manager to run whenever we invoke the property's key.</p>
<p>So, for instance, running <code>npm run dev</code> will execute the <code>"webpack --mode development"</code> command.</p>
<h4 id="heading-keywords">keywords</h4>
<p>The <code>"keywords"</code> field specifies an array of keywords that can help people discover your package.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"keywords"</span>: [
    <span class="hljs-string">"drag"</span>,
    <span class="hljs-string">"drop"</span>,
    <span class="hljs-string">"drag and drop"</span>,
    <span class="hljs-string">"dragndrop"</span>,
    <span class="hljs-string">"draggable"</span> 
  ]
}
</code></pre>
<p>The <code>"keywords"</code> property is part of the information shown when people run the <code>npm search</code> command.</p>
<h4 id="heading-author">author</h4>
<p>The <code>"author"</code> field lists a project's author's details.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Oluwatobi Sofela &lt;oluwatobiss@codesweetly.com&gt; (https://www.codesweetly.com)"</span>
}
</code></pre>
<p>You can also write the snippet above as:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"author"</span>: {
    <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Oluwatobi Sofela"</span>,
    <span class="hljs-attr">"email"</span>: <span class="hljs-string">"oluwatobiss@codesweetly.com"</span>,
    <span class="hljs-attr">"url"</span>: <span class="hljs-string">"https://www.codesweetly.com"</span>
  }
}
</code></pre>
<p>Note that the <code>"email"</code> and <code>"url"</code> properties are optional.</p>
<h4 id="heading-dependencies">dependencies</h4>
<p>The <code>"dependencies"</code> field lists all the packages a project depends on in production.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"first-package"</span>: <span class="hljs-string">"^1.0.4"</span>,
    <span class="hljs-attr">"second-package"</span>: <span class="hljs-string">"~2.1.3"</span>
  }
}
</code></pre>
<p>So, whenever a user installs your project from the NPM registry, the dependencies property ensures package managers can automatically find and install the packages listed.</p>
<p>Note that you can add a package to the <code>"dependencies"</code> field through either of the following ways:</p>
<ul>
<li>Manually add the name and the <a target="_blank" href="https://docs.npmjs.com/about-semantic-versioning">semantic version</a> of each package your project depends on in production.</li>
<li>Run the <code>npm install package-name --save-prod</code> command on your terminal. Or <code>yarn add package-name</code> if Yarn is your package manager.</li>
</ul>
<h4 id="heading-devdependencies">devDependencies</h4>
<p>The <code>"devDependencies"</code> field lists all the packages a project does not need in production—but requires for its local development and testing purposes.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"first-dev-package"</span>: <span class="hljs-string">"^5.8.1"</span>,
    <span class="hljs-attr">"second-dev-package"</span>: <span class="hljs-string">"3.2.2—4.0.0"</span>
  }
}
</code></pre>
<p>Note that the packages listed in the <code>"devDependencies"</code> field will be available in the project's development environment but not on its production server.</p>
<p>Suppose a user installs the project through the <code>npm install</code> (or <code>yarn add</code>) command. In such a case, the package manager will find and download all the listed <code>devDependencies</code> to the project's <code>node_modules</code> directory.</p>
<p>Keep in mind that you can add a package to the <code>"devDependencies"</code> field through either of the following ways:</p>
<ul>
<li>Manually add the name and the semantic version of each package on which your project depends for its development and testing purposes.</li>
<li>Run the <code>npm install package-name --save-dev</code> command on your terminal. Or <code>yarn add package-name --dev</code> if Yarn is your package manager.</li>
</ul>
<h4 id="heading-homepage">homepage</h4>
<p>The <code>"homepage"</code> field specifies the URL to your project's homepage.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"homepage"</span>: <span class="hljs-string">"https://codesweetly.com/package-json-file-explained"</span>
}
</code></pre>
<p>So, now that we know what a <code>package.json</code> file is, we can discuss <code>package-lock.json</code>.</p>
<h2 id="heading-what-is-a-package-lockjson-file">What Is a <code>package-lock.json</code> File?</h2>
<p>The <strong>package-lock.json</strong> file is a <a target="_blank" href="https://www.codesweetly.com/document-vs-data-vs-code/#h-what-is-a-document">document</a> NPM uses to record the exact version of all the packages you've installed locally to your project's <code>node_modules</code> directory.</p>
<p>A <code>package-lock.json</code> file makes an app 100% reproducible in the exact way you published it to the NPM registry.</p>
<p>So, suppose a user clones your app and runs the <code>npm install</code> command. In such a case, <code>package-lock.json</code> ensures that the user downloads the exact version of the packages you used to develop the application.</p>
<p>For instance, let's say a user cloned your app containing <em>no</em> <code>package-lock.json</code> file, and a dependency used in the app has a newer version.</p>
<p>Suppose the dependency's version number in the <code>package.json</code> file has a caret sign (for example, <code>^2.6.2</code>). In that case, NPM will install the latest minor version of the dependency—which might cause the app to produce erroneous results.</p>
<p>However, suppose the user cloned your app containing a <code>package-lock.json</code> file. In that case, NPM will install the exact version of the dependency as recorded in the <code>package-lock.json</code> file—regardless of whether a newer version exists.</p>
<p>Therefore, users will always get your app the precise way you published it to the NPM registry.</p>
<p>In other words, NPM uses the <code>package-lock.json</code> file to lock your package's dependencies to the specific version numbers you used for the project's development.</p>
<p><strong>Note:</strong> NPM will update the packages recorded in the <code>package-lock.json</code> file whenever you run the <code>npm update</code> command.</p>
<h2 id="heading-what-is-a-yarnlock-file">What Is a <code>yarn.lock</code> File?</h2>
<p>The <code>yarn.lock</code> file is a document Yarn uses to record the exact version of all the packages you've installed locally to your project's <code>node_modules</code> directory.</p>
<p>The <code>yarn.lock</code> file is comparable to NPM's <a class="post-section-overview" href="#heading-what-is-a-package-lockjson-file">package-lock.json</a> lockfile.</p>
<p>We earlier mentioned that your package manager does not execute an installed package—you must explicitly do so yourself. Let's discuss how.</p>
<h2 id="heading-how-to-run-an-executable-package">How to Run an Executable Package</h2>
<p>There are several ways to run an executable package. Below are the standard techniques.</p>
<h3 id="heading-manually-locate-and-execute-the-package">Manually locate and execute the package</h3>
<p>One way to run an executable package is to type its local path on your command line like so:</p>
<pre><code class="lang-bash">./node_modules/.bin/package-name
</code></pre>
<h3 id="heading-add-the-package-to-the-packagejsons-scripts-field">Add the package to the package.json's <code>scripts</code> field</h3>
<p>An alternate way to execute a package is to first add it to the <code>"scripts"</code> field of your project's package.json file like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"your_package"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"desired-name"</span>: <span class="hljs-string">"name-of-package-to-execute"</span>
  }
}
</code></pre>
<p>Afterward, you can run the package like so:</p>
<pre><code class="lang-bash">npm run desired-name
</code></pre>
<p>Note that the command above is shorthand for <code>npm run-script desired-name</code>.</p>
<p>Alternatively, you can execute the package with Yarn like so:</p>
<pre><code class="lang-bash">yarn run desired-name
</code></pre>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"codesweetly-app"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"webpack"</span>,
  }
}
</code></pre>
<p>The snippet above added <a target="_blank" href="https://www.codesweetly.com/javascript-module-bundler/">webpack</a> to your <code>package.json</code>'s <code>"scripts"</code> field. So, we can now execute <code>webpack</code> on the command line like this:</p>
<pre><code class="lang-bash">npm run build
</code></pre>
<p>Or, if your package manager is Yarn, you can run webpack like this:</p>
<pre><code class="lang-bash">yarn run build
</code></pre>
<h3 id="heading-use-npx">Use NPX</h3>
<p>A faster way to run an executable package is to use NPX like so:</p>
<pre><code class="lang-bash">npx package-name
</code></pre>
<p>With NPX, you no longer need to add your package to the <code>"scripts"</code> field of your project's <code>package.json</code> file.</p>
<p>NPX (Node Package Execute) is a <a target="_blank" href="https://nodejs.dev/learn/the-npx-nodejs-package-runner">Node package runner</a> that automatically finds and executes a specified package.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-bash">npx webpack
</code></pre>
<p>The command above will automatically find and execute <a target="_blank" href="https://www.codesweetly.com/javascript-module-bundler/">webpack</a>. So, we do not need to add the <code>"build": "webpack"</code> property to the <code>"scripts"</code> field of our <code>package.json</code> file.</p>
<p><strong>Note:</strong> NPX automatically gets installed when you install Node 8.2/NPM 5.2.0 or higher.</p>
<p>You can also run some code using your preferred Node.js version. Let's find out how.</p>
<h2 id="heading-how-to-run-code-using-your-preferred-nodejs-version">How to Run Code Using Your Preferred Node.js Version</h2>
<p>You can use the <code>@</code> character and the <a target="_blank" href="https://www.npmjs.com/package/node">node npm package</a> to specify the Node.js version you wish to use to execute your code.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-bash">npx node@7 index.js
</code></pre>
<p>The snippet above tells NPX to run <code>index.js</code> with the latest version of Node from version 7 major.</p>
<p>Using the <code>node@</code> command is a helpful way to avoid using Node.js version management tools like <a target="_blank" href="https://github.com/nvm-sh/nvm">nvm</a> to switch between Node versions.</p>
<p>Suppose you wish to confirm the Node version NPX will use to run your code. In that case, run:</p>
<pre><code class="lang-bash">npx node@7 -v
</code></pre>
<p>The snippet above will display the latest Node version from version 7 major that NPX will use to run your code—for example, <code>v7.10.1</code>.</p>
<h2 id="heading-how-to-check-for-outdated-local-packages">How to Check for Outdated Local Packages</h2>
<p>To determine if any of your project's packages are outdated, run:</p>
<pre><code class="lang-bash">npm outdated
</code></pre>
<p>If the command outputs nothing, it means all your project's packages are up to date.</p>
<p>Otherwise, see this <a target="_blank" href="https://docs.npmjs.com/cli/v6/commands/npm-outdated">npm-outdated article</a> for a detailed explanation of the command's output.</p>
<p>Alternatively, you can use Yarn like so:</p>
<pre><code class="lang-bash">yarn outdated
</code></pre>
<p><strong>Note:</strong> To check a specific package's outdated status, add the package's name after the <code>outdated</code> keyword—for example, <code>npm outdated lodash</code>.</p>
<h2 id="heading-how-to-check-for-outdated-global-packages">How to Check for Outdated Global Packages</h2>
<p>To confirm which global package is outdated, run:</p>
<pre><code class="lang-bash">npm outdated -g --depth=0
</code></pre>
<h2 id="heading-how-to-check-for-locally-installed-packages">How to Check for Locally Installed Packages</h2>
<p>Here are three ways to check for locally installed packages:</p>
<h3 id="heading-locally-installed-packages-and-their-dependencies">Locally installed packages and their dependencies</h3>
<pre><code class="lang-bash">npm list
</code></pre>
<p>Or use Yarn like so:</p>
<pre><code class="lang-bash">yarn list
</code></pre>
<h3 id="heading-locally-installed-packageswithout-their-dependencies">Locally installed packages—without their dependencies</h3>
<pre><code class="lang-bash">npm list --depth=0
</code></pre>
<p>Or,</p>
<pre><code class="lang-bash">yarn list --depth=0
</code></pre>
<h3 id="heading-check-if-a-specific-package-got-installed-locally">Check if a specific package got installed locally</h3>
<pre><code class="lang-bash">npm list package-name
</code></pre>
<h2 id="heading-how-to-check-for-globally-installed-packages">How to Check for Globally Installed Packages</h2>
<p>Here are three ways to check for globally installed packages:</p>
<h3 id="heading-globally-installed-packages-and-their-dependencies">Globally installed packages and their dependencies</h3>
<pre><code class="lang-bash">npm list -g
</code></pre>
<p>Or use Yarn like so:</p>
<pre><code class="lang-bash">yarn list -g
</code></pre>
<h3 id="heading-globally-installed-packageswithout-their-dependencies">Globally installed packages—without their dependencies</h3>
<pre><code class="lang-bash">npm list -g --depth=0
</code></pre>
<p>Or,</p>
<pre><code class="lang-bash">yarn list -g --depth=0
</code></pre>
<h3 id="heading-check-if-a-specific-package-got-installed-globally">Check if a specific package got installed globally</h3>
<pre><code class="lang-bash">npm list -g package-name
</code></pre>
<h2 id="heading-how-to-update-packages">How to Update Packages</h2>
<p>Here's how to update packages with NPM and Yarn:</p>
<h3 id="heading-how-to-update-a-specific-package-to-its-latest-version">How to update a specific package to its latest version</h3>
<pre><code class="lang-bash">npm update package-name
</code></pre>
<p>Or, for projects managed with Yarn, run:</p>
<pre><code class="lang-bash">yarn upgrade package-name
</code></pre>
<h3 id="heading-how-to-update-all-of-a-projects-locally-installed-packages">How to update all of a project's locally installed packages</h3>
<pre><code class="lang-bash">npm update
</code></pre>
<p>Or,</p>
<pre><code class="lang-bash">yarn upgrade
</code></pre>
<h3 id="heading-how-to-update-a-specific-globally-installed-package">How to update a specific globally installed package</h3>
<p>You can update a globally installed package like this:</p>
<pre><code class="lang-bash">npm update package-name -g
</code></pre>
<h3 id="heading-how-to-update-all-your-systems-globally-installed-packages">How to update all your system's globally installed packages</h3>
<pre><code class="lang-bash">npm update -g
</code></pre>
<h2 id="heading-how-to-uninstall-packages">How to Uninstall Packages</h2>
<p>Here's how to uninstall packages with NPM and Yarn:</p>
<h3 id="heading-how-to-uninstall-a-package-from-a-specific-project">How to uninstall a package from a specific project</h3>
<p>First, navigate to the project's <a target="_blank" href="https://www.codesweetly.com/web-tech-glossary/#h-root-directory">root directory</a> from the command line and run:</p>
<pre><code class="lang-bash">npm uninstall package-name
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li>Add the <code>-S</code> (or <code>--save</code>) flag to remove references to the package in the <code>dependencies</code> field of the project's <code>package.json</code> file.</li>
<li>Add the <code>-D</code> (or <code>--save-dev</code>) flag to remove references to the package in the <code>devDependencies</code> field of the project's <code>package.json</code> file.</li>
</ul>
<p>For projects managed with Yarn, run:</p>
<pre><code class="lang-bash">yarn remove package-name
</code></pre>
<p><strong>Note:</strong> The <code>yarn remove</code> command will automatically update the project's <code>package.json</code> and <code>yarn.lock</code> files.</p>
<h3 id="heading-how-to-uninstall-a-global-package">How to uninstall a global package</h3>
<pre><code class="lang-bash">npm uninstall package-name -g
</code></pre>
<p>Note that it is best practice not to remove packages manually from the <code>node_modules</code> folder as such action can affect other <em>modules</em> depending on it.</p>
<p>But what exactly is a module in NodeJS? Let's find out below.</p>
<h2 id="heading-what-exactly-is-a-module-in-nodejs">What Exactly Is a Module in NodeJS?</h2>
<p>A <strong>module</strong> in NodeJS is any file in the <code>node_modules</code> folder that the computer can load through Node's <code>require()</code> function.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> myModule = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./codesweetly.js"</span>);
</code></pre>
<p>Suppose the computer successfully used the <code>require()</code> function to load the <code>codesweetly.js</code> file. In such a case, it means <code>codesweetly.js</code> is a module—assigned to the <code>myModule</code> variable.</p>
<p>Keep in mind that a module may also be a package—but not always.</p>
<p>A module is <em>not</em> a package if it does <em>not</em> have a <code>package.json</code> file used to record information about it.</p>
<p>Also, note that for a module to be loadable by the <code>require()</code> function, the module must be one of the following:</p>
<ul>
<li>A package—whose <code>package.json</code> file contains a <code>"main"</code> field.</li>
<li>A JavaScript file.</li>
</ul>
<h2 id="heading-how-to-publish-your-project-to-the-npm-registry">How to Publish Your Project to the NPM Registry</h2>
<p>NPM is a free registry for <a target="_blank" href="https://www.npmjs.com/products">public package authors</a>.</p>
<p>So, you can use it to publish any project (folder) from your computer that has a <code>package.json</code> file.</p>
<p>Below are the steps required to share your package with the world.</p>
<h3 id="heading-step-1-sign-in-or-sign-up">Step 1: Sign in or sign up</h3>
<p>Go to the <a target="_blank" href="https://www.npmjs.com/">NPM website</a> and sign in (or sign up if you do not yet have an account).</p>
<p><strong>Note:</strong> make sure that you verify your email after creating a new account. Otherwise, you will get a <code>403 Forbidden</code> error while publishing your package.</p>
<h3 id="heading-step-2-log-in">Step 2: Log in</h3>
<p>Login to your NPM account from the command line like so:</p>
<pre><code class="lang-bash">npm login
</code></pre>
<p><strong>Note:</strong> You can use the <code>npm whoami</code> command to check if you are currently logged in.</p>
<h3 id="heading-step-3-publish-your-package">Step 3: Publish your package!</h3>
<p>Go to your project's root directory and publish it like so:</p>
<pre><code class="lang-bash">npm publish
</code></pre>
<p>Make sure that your package's name does not currently exist on NPM. Otherwise, you will get an error while publishing.</p>
<p>You can use the <code>npm search</code> command (or the <a target="_blank" href="https://www.npmjs.com/">NPM website</a>'s search bar) to search if the name you wish to use already exists on NPM.</p>
<p>Suppose all the suitable names for your package are already taken. In that case, NPM allows you to publish your project as a scope.</p>
<p>In other words, you can publish your package as a sub-section of your username. Let's see how below.</p>
<h3 id="heading-how-to-publish-your-package-as-a-scope-of-your-username">How to publish your package as a scope of your username</h3>
<p>Open your <code>package.json</code> file and prefix your package's name with your username.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"@username/package-name"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"MIT"</span>
}
</code></pre>
<p>NPM's default setting assumes that a scoped name package is a private project. So, you will get an error if you use the <code>npm publish</code> command to share a scoped name package.</p>
<p>Therefore, to publish your package as a scope of your username, add the <code>--access=public</code> flag to the <code>npm publish</code> command:</p>
<pre><code class="lang-bash">npm publish --access=public
</code></pre>
<p><strong>Note:</strong> You can make your project a scoped package during the initialization process by using the <code>npm init --scope=username</code> command instead of <code>npm init</code>.</p>
<h2 id="heading-overview">Overview</h2>
<p>This article discussed what a package manager is. We also looked at how two popular package managers (NPM and Yarn) work.</p>
<p>Thanks for reading!</p>
<h3 id="heading-and-heres-a-useful-reactjs-resource"><strong>And here's a useful ReactJS resource:</strong></h3>
<p>I wrote a book about React!</p>
<ul>
<li>It's beginners friendly ✔</li>
<li>It has live code snippets ✔</li>
<li>It contains scalable projects ✔</li>
<li>It has plenty of easy-to-grasp examples ✔</li>
</ul>
<p>The <a target="_blank" href="https://amzn.to/30iVPIG">React Explained Clearly</a> book is all you need to understand ReactJS.</p>
<p><a target="_blank" href="https://amzn.to/30iVPIG"><img src="https://www.freecodecamp.org/news/content/images/2022/01/Twitter-React_Explained_Clearly-CodeSweetly-Oluwatobi_Sofela.jpg" alt="React Explained Clearly Book Now Available at Amazon" width="600" height="400" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Force Use Yarn or NPM ]]>
                </title>
                <description>
                    <![CDATA[ By Carol-Theodor Pelu In this short post, I’m going to show you how to prevent the usage of npm or yarn, depending on your needs.  This comes in handy when your team or organization has a preference for a specific package manager.  With this method, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-force-use-yarn-or-npm/</link>
                <guid isPermaLink="false">66d45dd78812486a37369c65</guid>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Yarn ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 17 Jun 2020 07:03:09 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/06/how-to-force-use-yarn-or-npm-facebook.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Carol-Theodor Pelu</p>
<p>In this short post, I’m going to show you how to prevent the usage of <em>npm</em> or <em>yarn,</em> depending on your needs. </p>
<p>This comes in handy when your team or organization has a preference for a specific package manager. </p>
<p>With this method, you make sure everyone will be using the same package manager.</p>
<p>Let’s get started!</p>
<p>Want to watch a video about how to do this? Check this one out:</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/RmpVlaocd0M" 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-edit-npmrc">Edit .npmrc</h2>
<p>You might not have this file in your codebase. If this is the case, create this file in the root folder of your application.</p>
<p>It allows us to specify package manager configurations and it is used by both <em>npm</em> and <em>yarn</em>.</p>
<p>Your <code>.npmrc</code> file should have the <code>engine-strict</code> property marked as <code>true</code>.</p>
<pre><code class="lang-config">//.npmrc file

engine-strict = true
</code></pre>
<p>This option tells the package manager to use the version of the engines we have specified in the <code>package.json</code> file.</p>
<h2 id="heading-edit-packagejson">Edit package.json</h2>
<p>Inside your <code>package.json</code> file you should add the <code>engines</code> section if you don’t currently have it.</p>
<pre><code class="lang-json">
<span class="hljs-comment">//package.json</span>
{ 
  ...
  <span class="hljs-attr">"engines"</span>: {
    <span class="hljs-attr">"npm"</span>: <span class="hljs-string">"please-use-yarn"</span>,
    <span class="hljs-attr">"yarn"</span>: <span class="hljs-string">"&gt;= 1.19.1"</span>
  },
  ...
}
</code></pre>
<p>In the above code, the <code>package.json</code> file uses a version of <code>yarn</code> 1.19.1 or greater.<br>But for <code>npm</code> we specify a version that doesn’t exist.</p>
<p>This way we make sure that when someone tries to use <code>npm</code> instead of <code>yarn</code>, they will receive an error that outputs ‘<code>please-use-yarn</code>‘.</p>
<h2 id="heading-running-npm-install">Running npm install</h2>
<p>Once you’ve done the above changes, try to run <code>npm install</code>.</p>
<p>You will receive an error that prevents you from using <code>npm</code>.</p>
<pre><code class="lang-bash">
npm ERR! code ENOTSUP
npm ERR! notsup Unsupported engine <span class="hljs-keyword">for</span> my-app@0.1.0: wanted: {<span class="hljs-string">"npm"</span>:<span class="hljs-string">"please-use-yarn"</span>,<span class="hljs-string">"yarn"</span>:<span class="hljs-string">"&gt;= 1.19.1"</span>} (current:
 {<span class="hljs-string">"node"</span>:<span class="hljs-string">"12.16.3"</span>,<span class="hljs-string">"npm"</span>:<span class="hljs-string">"6.14.4"</span>})
npm ERR! notsup Not compatible with your version of node/npm: my-app@0.1.0
npm ERR! notsup Not compatible with your version of node/npm: my-app@0.1.0
npm ERR! notsup Required: {<span class="hljs-string">"npm"</span>:<span class="hljs-string">"please-use-yarn"</span>,<span class="hljs-string">"yarn"</span>:<span class="hljs-string">"&gt;= 1.19.1"</span>}
npm ERR! notsup Actual:   {<span class="hljs-string">"npm"</span>:<span class="hljs-string">"6.14.4"</span>,<span class="hljs-string">"node"</span>:<span class="hljs-string">"12.16.3"</span>}

npm ERR! A complete <span class="hljs-built_in">log</span> of this run can be found <span class="hljs-keyword">in</span>:
npm ERR!     C:\Users\YourUser\AppData\Roaming\npm-cache\_logs\2020-05-21T10_21_04_676Z-debug.log
</code></pre>
<p>This, of course, can be done the other way around if you want to prevent the usage of <code>yarn</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>It is pretty straightforward and easy to ensure that only one package manager must be used inside your project.  </p>
<p>This will reduce the chance of errors caused by developers that are using different package managers and it is a good practice to standardize the project’s coding rules and management.</p>
<p>You can reach out and ask me anything on <a target="_blank" href="https://twitter.com/pelu_carol">Twitter</a>, <a target="_blank" href="https://www.facebook.com/neutrondevcom">Facebook</a> and my <a target="_blank" href="https://neutrondev.com/">website</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create a Custom React Hook and Publish it to npm ]]>
                </title>
                <description>
                    <![CDATA[ Hooks are a handy addition to the React API that allow us to organize some of our logic and state in function components. How can we build a custom hook and share it with the rest of the world? What are hooks? Why are custom hooks cool? What are we ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-a-custom-react-hook-and-publish-it-to-npm/</link>
                <guid isPermaLink="false">66b8e34f682e4a25eed261a0</guid>
                
                    <category>
                        <![CDATA[ front end ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Front-end Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ frontend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm scripts ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ react hooks ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Yarn ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Colby Fayock ]]>
                </dc:creator>
                <pubDate>Tue, 14 Apr 2020 14:45:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/07/Custom-React-Hooks-Book-Cover--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hooks are a handy addition to the React API that allow us to organize some of our logic and state in function components. How can we build a custom hook and share it with the rest of the world?</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-are-hooks">What are hooks?</a></li>
<li><a class="post-section-overview" href="#heading-why-are-custom-hooks-cool">Why are custom hooks cool?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-we-going-to-make">What are we going to make?</a></li>
<li><a class="post-section-overview" href="#heading-step-0-naming-your-hook">Step 0: Naming your hook</a></li>
<li><a class="post-section-overview" href="#heading-step-1-setting-up-your-project">Step 1: Setting up your project</a></li>
<li><a class="post-section-overview" href="#heading-step-2-writing-your-new-react-hook">Step 2: Writing your new React Hook</a></li>
<li><a class="post-section-overview" href="#heading-step-3-using-your-react-hook-in-an-example">Step 3: Using your React hook in an example</a></li>
<li><a class="post-section-overview" href="#heading-step-4-compiling-your-react-hook-and-example">Step 4: Compiling your React hook and Example</a></li>
<li><a class="post-section-overview" href="#heading-step-5-publishing-your-react-hook-to-npm">Step 5: Publishing your React hook to npm</a></li>
<li><a class="post-section-overview" href="#heading-more-resources-about-hooks">More resources about hooks</a></li>
</ul>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/Q0xVnRanXVk" 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-hooks">What are hooks?</h2>
<p>React <a target="_blank" href="https://reactjs.org/docs/hooks-intro.html">hooks</a> in simple terms are functions. When you include them in your component or within another hook, they allow you to make use of React internals and parts of the React lifecycle with native hooks like <code>useState</code> and <code>useEffect</code>.</p>
<p>I don’t plan on doing a deep dive about hooks, but you can <a target="_blank" href="https://www.freecodecamp.org/news/how-to-destructure-the-fundamentals-of-react-hooks-d13ff6ea6871/">check out a quick introduction</a> with an example of <code>useState</code> as well as <a target="_blank" href="https://reactjs.org/docs/hooks-intro.html">the intro from the React team</a>.</p>
<h2 id="heading-why-are-custom-hooks-cool">Why are custom hooks cool?</h2>
<p>The great thing about creating custom hooks is they allow you to abstract logic for your components making it easier to reuse across multiple components in your app.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/hook-example-use-counter-1.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Hook diagram example for useCounter</em></p>
<p>For instance, if you wanted to create a simple counter where you use React’s state to manage the current count. Instead of having the same <code>useState</code> hook in each component file, you can create that logic once in a <code>useCounter</code> hook, making it easier to maintain, extend, and squash bugs if they come up.</p>
<h2 id="heading-what-are-we-going-to-make">What are we going to make?</h2>
<p>For the purposes of this article, we’re going to keep it simple with a basic hook. Typically, you might use a hook because rather than a typical function, you use other native hooks that are required to be used within React function components. We’re going to stick with some basic input and output to keep things simple.</p>
<p>We’re going to recreate this custom <a target="_blank" href="https://github.com/colbyfayock/use-placecage">Placecage hook</a> I made, that allows you to easily generate image URLs that you can use as placeholder images.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/nic-cage-excited.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Nic Cage excited</em></p>
<p>If you’re not familiar, <a target="_blank" href="https://www.placecage.com/">Placecage</a> is an API that allows you to generate pictures of Nic Cage as placeholder images for your website. Silly? Yes. Fun? Absolutely!</p>
<p>But if you’re not a fan of Nic's work, you can just as easily swap in the URL for <a target="_blank" href="https://placeholder.com/">Fill Murray</a> which uses pictures of Bill Murray or <a target="_blank" href="https://placeholder.com/">placeholder.com</a> which generates simple solid color background with text that shows the size of the image.</p>
<h2 id="heading-step-0-naming-your-hook">Step 0: Naming your hook</h2>
<p>Before we jump in to our actual code, our ultimate goal is to publish this hook. If that’s not your goal, you can skip this step, but for publishing, we’ll want to create a name for our hook.</p>
<p>In our case, our hook name will be <code>usePlaceCage</code>. Now with that in mind, we have 2 formats of our name — one in camelCase format and one in snake-case format.</p>
<ul>
<li><strong>camelCase:</strong> usePlaceCage</li>
<li><strong>snake-case:</strong> use-placecage</li>
</ul>
<p>The camelCase format will be used for the actual hook function, where the snake-case name will be used for the package name and some of the folders. When creating the name, keep in mind that the package name must be unique. If a package with the same name exists on <a target="_blank" href="https://www.npmjs.com/">npmjs.com</a> already, you won't be able to use it.</p>
<p>If you don’t already have a name, it's okay! You can just use your own name or something you can think of, it doesn’t really matter too much as really we're just trying to learn how to do this. If it were me for instance, I would use:</p>
<ul>
<li><strong>camelCase:</strong> useColbysCoolHook</li>
<li><strong>snake-case:</strong> use-colbyscoolhook</li>
</ul>
<p>But just to clarify, for the rest of our example, we’re going to stick with <code>usePlaceCage</code> and <code>use-placecage</code>.</p>
<h2 id="heading-step-1-setting-up-your-project">Step 1: Setting up your project</h2>
<p>Though you can set up your project however you’d like, we’re going to walk through building a new hook from <a target="_blank" href="https://github.com/colbyfayock/use-custom-hook">this template</a> I created.</p>
<p>The hope here, is that we can take out some of the painful bits of the process and immediately get productive with our custom hook. Don’t worry though, I’ll explain what’s going on along the way.</p>
<p>The requirements here are <a target="_blank" href="https://git-scm.com/">git</a> and <a target="_blank" href="https://yarnpkg.com/">yarn</a> as it helps provide tools that make it easy to scaffold this template, such as using the workspaces feature to allow easy npm scripts to manage the code from the root of the project. If either of those are a dealbreaker, you can try downloading the repo via the download link and update it as needed.</p>
<h3 id="heading-cloning-the-hook-template-from-git">Cloning the hook template from git</h3>
<p>To start, let’s clone the repository from Github. In the command below, you should replace <code>use-my-custom-hook</code> with the name of your hook, such as <code>use-cookies</code> or <code>use-mooncake</code>.</p>
<pre><code class="lang-shell">git clone https://github.com/colbyfayock/use-custom-hook use-my-custom-hook
cd use-my-custom-hook
</code></pre>
<p>Once you clone and navigate to that folder, you should now see 2 directories – an <code>example</code> directory and a <code>use-custom-hook</code> directory.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/cloning-use-custom-hook-1.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Cloning use-custom-hook</em></p>
<p>This will give you a few things to get started:</p>
<ul>
<li>A hook directory that will include the source for our hook</li>
<li>Build scripts that compile our hook with <a target="_blank" href="https://babeljs.io/">babel</a></li>
<li>An example page that imports our hook and creates a simple demo page with <a target="_blank" href="https://nextjs.org/">next.js</a></li>
</ul>
<h3 id="heading-running-the-hook-setup-scripts">Running the hook setup scripts</h3>
<p>After we successfully clone the repo, we want to run the setup scripts which install dependencies and update the hook to the name we want.</p>
<pre><code class="lang-shell">yarn install &amp;&amp; yarn setup
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/setting-up-new-hook-template.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Setting up a new hook from the use-custom-hook template</em></p>
<p>When the setup script runs, it will do a few things:</p>
<ul>
<li>It will ask you for your name – this is used to update the LICENSE and the package's author name</li>
<li>It will ask you for your hook's name in 2 variations – camelCase and snake-case - this will be used to update the name of the hook throughout the template and move files with that name to the correct location</li>
<li>It will reset git – it will first remove the local .git folder, which contains the history from my template and reinitialize git with a fresh commit to start your new history in</li>
<li>Finally, it will remove the setup script directory and remove the package dependencies that were only being used by those scripts</li>
</ul>
<h3 id="heading-starting-the-development-server">Starting the development server</h3>
<p>Once the setup scripts finish running, you'll want to run:</p>
<pre><code class="lang-shell">yarn develop
</code></pre>
<p>This runs a watch process on the hook source, building the hook locally each time a source file is changed, and running the example app server, where you can test the hook and make changes to the example pages.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/custom-hook-development-server.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Starting up the use-custom-hook development server</em></p>
<p>With this all ready, we can get started!</p>
<p><a target="_blank" href="https://github.com/colbyfayock/use-my-custom-hook/commits/master">Follow along with the commit!</a></p>
<h2 id="heading-step-2-writing-your-new-react-hook">Step 2: Writing your new React Hook</h2>
<p>At this point, you should now have a new custom hook where you can make it do whatever you'd like. But since we're going to walk through rebuilding the <a target="_blank" href="https://github.com/colbyfayock/use-placecage">usePlaceCage</a> hook, let's start there.</p>
<p>The usePlaceCage hook does 1 simple thing from a high level view – it takes in a configuration object and returns a number of image URLs that you can then use for your app.</p>
<p>Just as a reminder, any time I mention <code>usePlaceCage</code> or <code>use-placecage</code>, you should use the hook name that you set up before.</p>
<h3 id="heading-a-little-bit-about-placecagecom">A little bit about placecage.com</h3>
<p>Placecage.com is a placeholder image service that does 1 thing. It takes a URL with a simple configuration and returns an image... of Nic Cage.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/placecage-website.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>placecage.com</em></p>
<p>From the simplest use, the service uses a URL pattern as follows:</p>
<pre><code>https:<span class="hljs-comment">//www.placecage.com/200/300</span>
</code></pre><p>This would return an image with a width of 200 and height of 300.</p>
<p>Optionally, you can pass an additional URL parameter that defines the type of image:</p>
<pre><code>https:<span class="hljs-comment">//www.placecage.com/gif/200/300</span>
</code></pre><p>In this particular instance, our type is <code>gif</code>, so we'll receive a gif.</p>
<p>The different types available to use are:</p>
<ul>
<li>Nothing: calm</li>
<li><code>g</code>: gray</li>
<li><code>c</code>: crazy</li>
<li><code>gif</code>: gif</li>
</ul>
<p>We'll use this to define how we set up configuration for our hook.</p>
<h3 id="heading-defining-our-core-generator-function">Defining our core generator function</h3>
<p>To get started, we're going to copy over a function at the bottom of our <code>use-placecage/src/usePlaceCage.js</code> file, which allows us to generate an image URL, as well as a few constant definitions that we'll use in that function.</p>
<p>First, let's copy over our constants to the top of our <code>usePlaceCage.js</code> file:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> PLACECAGE_HOST = <span class="hljs-string">'https://www.placecage.com/'</span>;
<span class="hljs-keyword">const</span> TYPES = {
  <span class="hljs-attr">calm</span>: <span class="hljs-literal">null</span>,
  <span class="hljs-attr">gray</span>: <span class="hljs-string">'g'</span>,
  <span class="hljs-attr">crazy</span>: <span class="hljs-string">'c'</span>,
  <span class="hljs-attr">gif</span>: <span class="hljs-string">'gif'</span>
};
<span class="hljs-keyword">const</span> DEFAULT_TYPE = <span class="hljs-string">'calm'</span>;
<span class="hljs-keyword">const</span> ERROR_BASE = <span class="hljs-string">'Failed to place Nick'</span>;
</code></pre>
<p>Here we:</p>
<ul>
<li>Define a host, which is the base URL of our image service.</li>
<li>Define the available types, which we'll use in the configuration API. We set <code>calm</code> to <code>null</code>, because it's the default value which you get by not including it at all</li>
<li>Our default type will be <code>calm</code></li>
<li>And we set an error base which is a consistent message when throwing an error</li>
</ul>
<p>Then for our function, let's copy this at the bottom of our <code>usePlaceCage.js</code> file:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateCage</span>(<span class="hljs-params">settings</span>) </span>{
  <span class="hljs-keyword">const</span> { type = DEFAULT_TYPE, width = <span class="hljs-number">200</span>, height = <span class="hljs-number">200</span>, count = <span class="hljs-number">1</span> } = settings;
  <span class="hljs-keyword">const</span> config = [];

  <span class="hljs-keyword">if</span> ( type !== DEFAULT_TYPE &amp;&amp; TYPES[type] ) {
    config.push(TYPES[type]);
  }

  config.push(width, height);

  <span class="hljs-keyword">if</span> ( <span class="hljs-built_in">isNaN</span>(count) ) {
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">`<span class="hljs-subst">${ERROR_BASE}</span>: Invalid count <span class="hljs-subst">${count}</span>`</span>);
  }

  <span class="hljs-keyword">return</span> [...new <span class="hljs-built_in">Array</span>(count)].map(<span class="hljs-function">() =&gt;</span> <span class="hljs-string">`<span class="hljs-subst">${PLACECAGE_HOST}</span><span class="hljs-subst">${config.join(<span class="hljs-string">'/'</span>)}</span>`</span>);
}
</code></pre>
<p>Walking through this code:</p>
<ul>
<li>We define a <code>generateCage</code> function which we'll use to generate our image URL</li>
<li>We take in a settings object as an argument, which defines the configuration of our image URL. We'll be using the same parameters as we saw in our placecage.com URL</li>
<li>We destructure those settings to make them available for us to use</li>
<li>We have a few defaults here just to make it easier. Our default <code>type</code> will be defined by <code>DEFAULT_TYPE</code> along with a default width, height, and number of results we want to return</li>
<li>We create a <code>config</code> array. We'll use this  to append all of the different configuration objects in our URL and finally join them together with a <code>/</code> essentially making a URL</li>
<li>Before we push our config to that array, we check if it's a valid argument, by using the <code>TYPES</code> object to check against it. If it's valid, we push it to our config array</li>
<li>We then push our width and height</li>
<li>We do some type checking, if we don't have a valid number as the <code>count</code>, we throw an error, otherwise we'll get incorrect results</li>
<li>Finally, we return a new array with the number of results requested, mapped to a URL creator, which uses <code>PLACECAGE_HOST</code> as our defined base URL, and with our config array joined by <code>/</code></li>
</ul>
<p>And if we were to test this function, it would look like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> cage = generateCage({
  <span class="hljs-attr">type</span>: <span class="hljs-string">'gif'</span>,
  <span class="hljs-attr">width</span>: <span class="hljs-number">500</span>,
  <span class="hljs-attr">height</span>: <span class="hljs-number">500</span>,
  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>
});

<span class="hljs-built_in">console</span>.log(cage); <span class="hljs-comment">// ['https://www.placecage.com/gif/500/500', 'https://www.placecage.com/gif/500/500']</span>
</code></pre>
<h3 id="heading-using-our-function-in-the-hook">Using our function in the hook</h3>
<p>So now that we have our generator function, let's actually use it in our hook!</p>
<p>Inside of the <code>usePlaceCage</code> function in the <code>use-placecage/src/usePlaceCage.js</code> file, we can add:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">usePlaceCage</span> (<span class="hljs-params">settings = {}</span>) </span>{
  <span class="hljs-keyword">return</span> generateCage(settings);
}
</code></pre>
<p>What this does it uses our generator function, takes in the settings that were passed into the hook, and returns that value from the hook.</p>
<p>Similar to our previous use example, if we were to use our hook, it would look like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> cage = usePlaceCage({
  <span class="hljs-attr">type</span>: <span class="hljs-string">'gif'</span>,
  <span class="hljs-attr">width</span>: <span class="hljs-number">500</span>,
  <span class="hljs-attr">height</span>: <span class="hljs-number">500</span>,
  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>
});

<span class="hljs-built_in">console</span>.log(cage); <span class="hljs-comment">// ['https://www.placecage.com/gif/500/500', 'https://www.placecage.com/gif/500/500']</span>
</code></pre>
<p>At this point, it does the same thing!</p>
<p>So now we have our hook, it serves as a function to generate image URLs for the placecage.com service. How can we actually use it?</p>
<p><a target="_blank" href="https://github.com/colbyfayock/use-my-custom-hook/commit/a4d4d3c3565759031c29d00faf731ac4c236a1fd">Follow along with the commit!</a></p>
<h2 id="heading-step-3-using-your-react-hook-in-an-example">Step 3: Using your React hook in an example</h2>
<p>The good news about our template, is it already includes an example app that we can update to easily make use of our hook to both test and provide documentation for those who want to use it.</p>
<h3 id="heading-setting-up-the-hook">Setting up the hook</h3>
<p>To get started, let's open up our <code>example/pages/index.js</code> file. Inside of this file you'll see the following:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> hookSettings = {
  <span class="hljs-attr">message</span>: <span class="hljs-string">'Hello, custom hook!'</span>
}

<span class="hljs-keyword">const</span> { message } = usePlaceCage(hookSettings);
</code></pre>
<p>This snippet is what was used by default in the template just for a proof of concept, so let's update that. We're going to use the same exact configuration as we did in Step 2:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> hookSettings = {
  <span class="hljs-attr">type</span>: <span class="hljs-string">'gif'</span>,
  <span class="hljs-attr">width</span>: <span class="hljs-number">500</span>,
  <span class="hljs-attr">height</span>: <span class="hljs-number">500</span>,
  <span class="hljs-attr">count</span>: <span class="hljs-number">2</span>
}

<span class="hljs-keyword">const</span> cage = usePlaceCage(hookSettings);
</code></pre>
<p>Again, we set up our settings object with the configuration for our hook and invoke our hook and set the value to the <code>cage</code> constant.</p>
<p>If we now console log that value our to our dev tools, we can see it working!</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'cage'</span>, cage);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/console-log-cage-array.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Using console.log to show the cage value</em></p>
<p><em>Note: If you get an error here about <code>message</code>, you  can comment that our or remove it under the Examples section.</em></p>
<h3 id="heading-updating-the-example-with-our-new-hook-configuration">Updating the example with our new hook configuration</h3>
<p>If you scroll down to the Examples section, you'll notice that we have the same default <code>hookSettings</code> as above, so let's update that again to make sure our example is accurate.</p>
<pre><code class="lang-jsx">{<span class="hljs-string">`const hookSettings = {
  type: 'gif',
  width: 500,
  height: 500,
  count: 2
}

const cage = usePlaceCage(hookSettings);`</span>}
</code></pre>
<p>You'll also notice that we're no longer using the <code>message</code> variable. If you didn't remove it in the last step, we can now replace it under the Output heading with:</p>
<pre><code class="lang-jsx">&lt;p&gt;
  { <span class="hljs-built_in">JSON</span>.stringify(cage) }
&lt;/p&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
  { cage.map((img, i) =&gt; <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{</span>`<span class="hljs-attr">img-</span>${<span class="hljs-attr">i</span>}`} <span class="hljs-attr">width</span>=<span class="hljs-string">{200}</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{img}</span> /&gt;</span>)}
<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>
</code></pre>
<p>We're doing 2 things here:</p>
<ul>
<li>Instead of showing the variable itself, we wrap it with <code>JSON.stringify</code> so that we can show the contents of the array</li>
<li>We also use the <code>map</code> function to loop over our image URLs in the <code>cage</code> constant and create a new image element for each. This let's us preview the output instead of just seeing the values</li>
</ul>
<p>And once you save and open your browser, you should now see your updated examples and output!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/custom-hook-example-page.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Custom hook example page</em></p>
<h3 id="heading-other-things-you-can-do-on-that-page">Other things you can do on that page</h3>
<p>Before moving on, you can also update a few other things that will be important for your hooks page:</p>
<ul>
<li>Update the <strong>How to use</strong> section with instructions</li>
<li>Add additional examples to make it easier for people to know what to do</li>
</ul>
<p>A  few things are also automatically pulled in from the <code>use-placecage/package.json</code> file. You can either update them there to make it easier to maintain or you can replace them in the example page:</p>
<ul>
<li><code>name</code>: Is used at the <code>&lt;h1&gt;</code> of the page</li>
<li><code>description</code>: Is used at the description under the <code>&lt;h1&gt;</code></li>
<li><code>repository.url</code>: Used to include a link to the repository</li>
<li><code>author</code>: The <code>name</code> and <code>url</code> are used to include a link at the bottom of the page</li>
</ul>
<p><a target="_blank" href="https://github.com/colbyfayock/use-my-custom-hook/commit/71ae57b562ad814d0ce862c22e247aa8c450b6cf">Follow along with the commit!</a></p>
<h2 id="heading-step-4-compiling-your-react-hook-and-example">Step 4: Compiling your React hook and Example</h2>
<p>The way we can make our hook work easily as an npm module is to compile it for others to use. We're using babel to do this.</p>
<p>Though the publish process already does this for us automatically with the <code>prepublishOnly</code> script in <code>use-placecage/package.json</code>, we can manually compile our hook using the <code>yarn build</code> command from the root of the project.</p>
<p>Along with compiling the hook, running <code>yarn build</code> will also compile the example page, allowing you to upload it wherever you'd like. After running that command, you should see an output of static HTML files in the <code>example/out</code> directory.</p>
<p>If you're looking for a recommendation, <a target="_blank" href="https://www.netlify.com/">Netlify</a> makes it easy to connect your <a target="_blank" href="https://github.com/">Github</a> account and deploy the static site.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/netlify-deployment-setup.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Deployment setup in Netlify</em></p>
<p><a target="_blank" href="https://use-my-custom-hook.netlify.com/">See the demo site deployed to Netlify!</a></p>
<h2 id="heading-step-5-publishing-your-react-hook-to-npm">Step 5: Publishing your React hook to npm</h2>
<p>Finally, if you're happy with your hook, it's time to publish!</p>
<p>npm makes this part really easy. The only prerequisite you need to have an npm account. With that account, let's log in:</p>
<pre><code class="lang-shell">npm login
</code></pre>
<p>Which will prompt you for your login credentials.</p>
<p>Next, let's navigate to our hook's directory, as our package configuration is there under <code>use-placecage/package.json</code>:</p>
<pre><code class="lang-shell">cd use-placecage
</code></pre>
<p>Then, we can simply publish!</p>
<pre><code class="lang-shell">npm publish
</code></pre>
<p>Keep in mind, that each package name needs to be unique. If you used <code>use-placecage</code>, it's already taken... by me. ?</p>
<p>But if you're successful, npm should build your hook and upload it to the package registry!</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/04/publishing-npm-package.jpg" alt="Image" width="600" height="400" loading="lazy">
<em>Publishing an npm package</em></p>
<p>It will then be available on npm with the following pattern:</p>
<pre><code>https:<span class="hljs-comment">//www.npmjs.com/package/[package-name]</span>
</code></pre><p>So for <code>use-placeage</code>, it's available here: <a target="_blank" href="https://www.npmjs.com/package/use-placecage">https://www.npmjs.com/package/use-placecage</a></p>
<h2 id="heading-we-now-have-a-custom-hook">We now have a custom hook!</h2>
<p>Yay ? if you followed along, you should now have created a custom hook and published it to npm.</p>
<p>Though this was a silly example using placecage.com, it gives us a good idea of how we can easily set this up.</p>
<p>You'll also notice that this specific example wasn't the best use case for a hooks, where we could have simply used a function. Typically, we'll want to use custom hooks to wrap functionality that can only live inside a React component, such as <code>useState</code>. To learn more about that, you can read one of my other <a target="_blank" href="https://www.freecodecamp.org/news/how-to-destructure-the-fundamentals-of-react-hooks-d13ff6ea6871/">articles about custom hooks</a>.</p>
<p>However, this gave us a good basis to talk through the creation and configuration of our new hook!</p>
<h2 id="heading-more-resources-about-hooks">More resources about hooks</h2>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-destructure-the-fundamentals-of-react-hooks-d13ff6ea6871/">How to destructure the fundamentals of React Hooks</a> (freecodecamp.org)</li>
<li><a target="_blank" href="https://reactjs.org/docs/hooks-intro.html">Introducing Hooks</a> (reactjs.org)</li>
<li><a target="_blank" href="https://reactjs.org/docs/hooks-reference.html">Hooks API Reference</a> (reactjs.org)</li>
</ul>
<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>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Getting rid of node_modules with Yarn Plug’n’Play ]]>
                </title>
                <description>
                    <![CDATA[ By Alcides Queiroz Reduce your install time up to 70%. Ask me how! ? Anyone who knows me can confirm that I’m a long-standing lover of JavaScript and its entire ecosystem. As a Front-end engineer, Node-based package managers have been a crucial part... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/getting-rid-of-node-modules-with-yarn-plugn-play-a490e5e747d7/</link>
                <guid isPermaLink="false">66c34b534f7405e6476b01c1</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Productivity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Yarn ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 09 Feb 2019 17:05:39 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*qYAlY8Iq5S4knk93upSneA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Alcides Queiroz</p>
<h4 id="heading-reduce-your-install-time-up-to-70-ask-me-how">Reduce your install time up to 70%. Ask me how! ?</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/F7mSgfClDgWzo8rkmxdF1mkiBw46HP5qbTRN" alt="Image" width="800" height="533" loading="lazy"></p>
<p>Anyone who knows me can confirm that I’m a long-standing lover of JavaScript and its entire <em>ecosystem</em>. As a Front-end engineer, Node-based package managers have been a crucial part of my toolset since 2013.</p>
<p>First, I used Bower, which was primarily focused on the front-end world. Then, in 2015, I sadly (ok, <em>not really</em>) realized that Bower was dying and NPM, the default package manager for Node, was the way to go for the front-end too. It was strange for me, at first, to use NPM for other things than Node modules, but I got used to the idea and migrated seamlessly.</p>
<p>Finally, just one year later, Facebook gave us Yarn, a modern and blazing fast alternative to NPM. I loved it at first sight! <strong>But some things were still problematic…</strong></p>
<h3 id="heading-inherited-problems-in-yarn">Inherited problems in Yarn</h3>
<p>Besides the speed, Yarn brought a number of advantages when compared to the NPM version at the time, such as lock files, offline mode, network resilience, checksums and others. Nevertheless, Yarn borrowed some known problems from NPM:</p>
<h4 id="heading-nodemodules-here-there-everywhere">node_modules here, there, everywhere</h4>
<p>For each project on your machine that uses NPM or Yarn, a <code>node_modules</code> folder is created. It doesn't matter if 10 projects use the exact same version of a given module, it will be copied over and over into each <code>node_modules</code> folder of these projects.</p>
<h4 id="heading-generating-a-new-nodemodules-folder-takes-a-really-long-time">Generating a new node_modules folder takes a really long time</h4>
<p>Even taking a great leap forward in terms of installation speed, Yarn was constrained by node_modules limitations. Just creating the node_modules folder takes up to 70% of the time needed to run <code>yarn install</code> (with a warm cache). <strong>It's a huge amount of files to be created on every installation.</strong> So, don't blame it on Yarn.</p>
<h4 id="heading-dependencies-not-added-to-packagejson">Dependencies not added to package.json</h4>
<p>Here’s a scenario for you: Your app works perfectly in development, but crashes in production. After hours of investigation, you finally realize that you forgot to add a dependency to your <code>package.json</code>. <strong>Yes, it can happen.</strong></p>
<h4 id="heading-slow-module-resolution-at-runtime">Slow module resolution at runtime</h4>
<p>The boot time of your app is heavily impacted by the way Node resolves dependencies. It wastes time querying the file system to discover where a given dependency will be resolved from.</p>
<h3 id="heading-yarn-plugnplay-to-the-rescue">Yarn Plug’n’Play to the rescue!</h3>
<p>All of the above problems were addressed by the Yarn team with the release of the Plug’n’Play feature last September.</p>
<p>When you enable PnP, instead of copying every needed file from the cache to the <code>node_modules</code> folder, here's what Yarn does:</p>
<ol>
<li>It creates a single file with static resolution tables. These tables will contain a bunch of important info, such as: packages available in the dependency tree, how they relate between themselves and their location on the disk.</li>
<li>A special resolver is used in order to help Node discovering where each dependency has been installed (under the Yarn cache folder). It solely relies on the resolution tables which were created previously. As these tables contain information about the entire dependency tree, the node_modules resolution process won’t need to make a lot of <code>stat</code> and <code>readdir</code> calls at runtime anymore, significantly reducing your app boot time. And as Yarn knows all of your dependencies, it will complain if you try to import a module that's not present in your <code>package.json</code>:</li>
</ol>
<p><img src="https://cdn-media-1.freecodecamp.org/images/08nON5DmVDa9ITAs2nhTlNoRqNug1C-pC1Zs" alt="Image" width="628" height="126" loading="lazy"></p>
<h3 id="heading-using-yarn-plugnplay">Using Yarn Plug’n’Play</h3>
<p>Converting a project to make use of PnP is easy as 1–2–3. You just need to add a <code>installConfig</code> section to your <code>package.json</code>, with a <code>pnp</code> key set to <code>true</code>, like this one:</p>
<pre><code>{    <span class="hljs-string">"installConfig"</span>: {     <span class="hljs-string">"pnp"</span>: <span class="hljs-literal">true</span>   }}
</code></pre><blockquote>
<p><strong>Note:</strong> You need Yarn v1.12+ in order to use Plug’n’Play.</p>
</blockquote>
<p>After that, just run <code>yarn install</code> and everything inside your <code>node_modules</code> folder will be deleted. From now on, every dependency will be resolved directly from Yarn's hot cache.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/PD4zmILDWgikOs6RcNxXQnmtKE8YPiu9oFwN" alt="Image" width="800" height="419" loading="lazy">
_“yarn install” clears your node<em>modules folder when PnP is enable</em></p>
<h4 id="heading-using-pnp-in-a-new-react-project-with-create-react-app">Using PnP in a new React project with create-react-app</h4>
<p>If you use create-react-app 2+, the good news is that it works great with Yarn Plug’n’Play! Just append the <code>--use-pnp</code> option to the <code>create-react-app</code> command and you're good to go:</p>
<pre><code>npx create-react-app your-app-name --use-pnp
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/Q1KEkqQk4isuWAQUSB-kXGTIdOwZRW9oW7Qw" alt="Image" width="644" height="918" loading="lazy"></p>
<h4 id="heading-possible-issues">Possible issues</h4>
<p>As nothing is perfect in the world, PnP may incur new issues when used in projects relying on a custom install logic. If you need more info about these potential new issues, <a target="_blank" href="https://github.com/yarnpkg/rfcs/files/2378943/Plugnplay.pdf">you can find a detailed explanation in this paper</a>.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Plug’n’Play solves some really annoying problems in Yarn. Besides, it dramatically improves dependency caching on CIs, saving installation time and allowing our builds to get right to the point: <strong>running the tests!</strong></p>
<p>And that’s it! Have fun with Yarn PnP.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
