<?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[ modules - 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[ modules - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Tue, 19 May 2026 10:29:20 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/modules/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Modules – How to Create, Import, and Export a Module in JS ]]>
                </title>
                <description>
                    <![CDATA[ By Dapo Adedire JavaScript, like most programming languages, was initially used for small tasks. But as its popularity grew, so did the amount of code that needed to be written.  Having a large amount of code in a single file can be problematic, so i... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-modules/</link>
                <guid isPermaLink="false">66d45e0136c45a88f96b7cd3</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 28 Feb 2023 20:42:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/Add-a-subheading--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dapo Adedire</p>
<p>JavaScript, like most programming languages, was initially used for small tasks. But as its popularity grew, so did the amount of code that needed to be written. </p>
<p>Having a large amount of code in a single file can be problematic, so it's helpful to split the code into multiple parts. This is where modules come in handy.</p>
<h2 id="heading-what-is-a-module">What is a Module?</h2>
<p>JavaScript modules are a way to organize and structure code. They allow developers to break their code into smaller, reusable pieces. You can think about them as smaller pieces of code that you can import and export between different parts of an application.</p>
<p>Throughout this article, we'll go through how use modules in your program and the best ways to do it.</p>
<p>But first, let's talk about some more reasons to use modules.</p>
<h2 id="heading-the-benefits-of-using-modules">The Benefits of Using Modules</h2>
<p>Your code will still run if you put it all in the same file. But you might be causing some problems for yourself. Let's talk about some benefits of using modules in your program.</p>
<h3 id="heading-more-organized-code">More Organized Code</h3>
<p>Using modules in your application makes everything well-sorted and arranged. It also makes your work easier to understand for anyone that wants to go through your code. </p>
<p>You probably wouldn't be excited to find a variable called "username" on line 431 or to need to start renaming a variable or function name everywhere it is used in an application.</p>
<h3 id="heading-code-reusability">Code Reusability</h3>
<p>By breaking down your code into smaller, modular components, you can easily reuse those components in other parts of your application or in entirely new applications. </p>
<p>This can save you a lot of time and effort, as you don't have to rewrite the same code over and over again. </p>
<p>Also, if you make changes to a module, those changes will be reflected everywhere that module is used, making it easier to maintain and update your codebase.</p>
<h3 id="heading-no-naming-conflicts">No Naming Conflicts</h3>
<p>Using JavaScript modules helps you avoid naming conflicts. When working on a large project, it's common for developers to write multiple functions and variables with the same name. This can lead to naming conflicts where two or more pieces of code have the same name, causing unexpected behavior and errors. With modules, you don't have this problem.</p>
<h2 id="heading-how-to-use-modules-in-javascript">How to Use Modules in JavaScript</h2>
<h3 id="heading-how-to-define-a-module">How to Define a Module</h3>
<p>Here is the basic way to define a module. Imagine 2 files names, <code>main.js</code> and <code>generate.js</code>.</p>
<p>Here's main.js:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Muhammad Ali"</span>
</code></pre>
<p>And here's generate.js:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateUserCertificate</span>(<span class="hljs-params">userName, date</span>): 
    # <span class="hljs-title">generate</span> <span class="hljs-title">user</span> <span class="hljs-title">certificate</span>. 
<span class="hljs-title">const</span> <span class="hljs-title">myName</span> = <span class="hljs-title">name</span>
<span class="hljs-title">generateUserCertificate</span>(<span class="hljs-params">myName, <span class="hljs-string">"2023-09-04"</span></span>)</span>
</code></pre>
<p>To use the "name" variable inside the generate.js file, you need to export it from the main.js file and import it into the generate.js file.</p>
<p>There are a lot of techniques you can use to import and export files.</p>
<p>We'll go through them one by one.</p>
<h2 id="heading-types-of-file-exports-in-javascript">Types of File Exports in JavaScript</h2>
<h3 id="heading-default-exports">Default Exports</h3>
<p>Here's how to perform a default export in a JavaScript file:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getAllUser</span>(<span class="hljs-params"></span>):

<span class="hljs-title">export</span> <span class="hljs-title">default</span> <span class="hljs-title">getAllUser</span></span>
</code></pre>
<p>Note that you can only use one default export in a JavaScript file. You can also export before the declaration, like this:</p>
<pre><code class="lang-javascript"><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">getAllUser</span>(<span class="hljs-params"></span>):</span>
</code></pre>
<p>This is easier to read, right?</p>
<h3 id="heading-named-exports">Named Exports</h3>
<p>Named exports allow you to share multiple modules from a file, unlike default exports which can only have one in a file. </p>
<p>You won't need to use the "default" syntax when using named exports. Named exports also need to be enclosed in curly brackets if you are exporting more than one module.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> name = <span class="hljs-string">"Muhammad Ali"</span>

<span class="hljs-keyword">export</span> name;
</code></pre>
<p>You can also export before the declaration. Here's how to do that:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHi</span>(<span class="hljs-params">user</span>) </span>{
  alert(<span class="hljs-string">`Hello, <span class="hljs-subst">${user}</span>!`</span>);
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">user</span>) </span>{
  alert(<span class="hljs-string">`Hello, <span class="hljs-subst">${user}</span>!`</span>);
}
</code></pre>
<p>You can also export multiple variables, functions, or classes using named exports in a single statement. Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> name = <span class="hljs-string">"Muhammad Alli"</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">user</span>) </span>{
  alert(<span class="hljs-string">`Hello, <span class="hljs-subst">${user}</span>!`</span>);
}

<span class="hljs-keyword">export</span> {name, sayHello};
</code></pre>
<p>Note: It is possible to have both default and named export in a module.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> age = <span class="hljs-number">404</span>;

<span class="hljs-keyword">const</span> name = <span class="hljs-string">"Muhammad Alli"</span>

<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">sayHello</span>(<span class="hljs-params">user</span>) </span>{
  alert(<span class="hljs-string">`Hello, <span class="hljs-subst">${user}</span>!`</span>);
}

<span class="hljs-keyword">export</span> {age, name};
</code></pre>
<h3 id="heading-how-to-rename-exports">How to Rename Exports</h3>
<p>It's also possible to rename your modules before exporting them. Here's how you'd do that:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">user</span>) </span>{
  alert(<span class="hljs-string">`Hello, <span class="hljs-subst">${user}</span>!`</span>);
}

<span class="hljs-keyword">export</span> { sayHello <span class="hljs-keyword">as</span> greet };
</code></pre>
<h2 id="heading-how-to-import-modules">How to Import Modules</h2>
<h3 id="heading-how-to-import-a-single-default-export">How to Import a Single Default Export</h3>
<p>Here is how to import a default export:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> getAllUser <span class="hljs-keyword">from</span> <span class="hljs-string">"getuser.js"</span>;
</code></pre>
<p>That's all – you can then proceed to use the <code>getAllUser</code> function anywhere in that file.</p>
<h3 id="heading-how-to-import-a-single-named-export">How to Import a Single Named Export</h3>
<p>Here is how to import a single named export.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {name} <span class="hljs-keyword">from</span> <span class="hljs-string">"username.js"</span>
</code></pre>
<h3 id="heading-how-to-import-multiple-named-exports">How to Import Multiple Named Exports</h3>
<p>Here is how to export multiple named exports.</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">import</span> {name, sayHello} <span class="hljs-keyword">from</span> <span class="hljs-string">'user.js'</span>
</code></pre>
<h3 id="heading-how-to-rename-imports">How to Rename Imports</h3>
<p>You can also rename exports before using them in a JavaScript file. Here's how to do it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> {userName <span class="hljs-keyword">as</span> name, greet <span class="hljs-keyword">as</span> sayHello} <span class="hljs-keyword">from</span> <span class="hljs-string">'user.js'</span>
</code></pre>
<p>It basically imports the name and 1sayHello1 module and renames them, so you can only make reference to "userName" and "greet" in this current module.</p>
<h3 id="heading-how-to-import-an-entire-module">How to Import an Entire Module</h3>
<p>What if there are a lot of modules to import and it's a waste of time to create a single line of named exports for them? Then you can export them this way:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> User <span class="hljs-keyword">from</span> <span class="hljs-string">'user.js'</span>
</code></pre>
<p>Here is how you can use it in the module exported to:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> User <span class="hljs-keyword">from</span> <span class="hljs-string">'user.js'</span>

User.name
User.sayHi
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Modules are a powerful feature in JavaScript that allow developers to organize and structure their code for improved readability and reusability. They also help you avoid naming conflicts. </p>
<p>By breaking down large codebases into smaller, manageable modules, developers can write more efficient and maintainable code. </p>
<p>This article has covered the basics of defining, exporting, and importing modules in JavaScript, including default exports, named exports, renaming exports, and importing entire modules. </p>
<p>By mastering the use of modules, you can take your JavaScript programming skills to the next level and write more efficient and scalable code.</p>
<p>You can share your thoughts with me on <a target="_blank" href="https://twitter.com/dapo_adedire">Twitter</a> here.</p>
<p>Happy coding! ^-^</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Create and Publish an NPM Package – a Step-by-Step Guide ]]>
                </title>
                <description>
                    <![CDATA[ NPM is the largest software registry on the internet. There are over a million packages in the NPM Library. Developers publish packages on NPM to share their code with others. And organisations also use NPM to share code internally. In this article, ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-create-and-publish-your-first-npm-package/</link>
                <guid isPermaLink="false">66d45ddaa3a4f04fb2dd2e33</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Wed, 01 Feb 2023 21:36:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/02/npm-package-article-image.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>NPM is the largest software registry on the internet. There are over a million packages in the NPM Library.</p>
<p>Developers publish packages on NPM to share their code with others. And organisations also use NPM to share code internally.</p>
<p>In this article, you will learn how to create a package. And you will also learn how to publish your package on NPM so others can download and use it.</p>
<p>Let's get started!</p>
<h2 id="heading-how-to-choose-a-name-for-your-npm-package">How to Choose a Name For Your NPM Package</h2>
<p>The first thing you need to do before creating your package is to choose a name. This is important because your package needs to have a unique name. You should choose a name that has not been used already.</p>
<p>When you decide on a name, go to the <a target="_blank" href="https://www.npmjs.com/">NPM registry</a> and run a search. Be sure there's no exact match to the name you chose (or a match that is too similar).</p>
<p>For example, if there's a package called <code>hellonpmpackage</code> and you decide to call yours <code>hello-npm-package</code>, NPM will throw an error when you attempt to publish it.</p>
<p>If there's already a package in the NPM registry with the same you want to use, then you have two options.</p>
<ol>
<li><p>You can choose a different name.</p>
</li>
<li><p>You can publish your package as a scoped package (see the section "Publishing scoped packages" below).</p>
</li>
</ol>
<h2 id="heading-how-to-create-a-npm-package">How to Create a NPM Package</h2>
<p>Follow the steps below to create your package.</p>
<h3 id="heading-1-install-node">1. Install Node</h3>
<p>If you do not already have Node installed, you should go ahead and install it. You can visit the official website to <a target="_blank" href="https://nodejs.org/en/download/">download and install Node.js</a>. NPM comes pre-installed with Node.</p>
<h3 id="heading-2-initialize-a-git-repository">2. Initialize a Git Repository</h3>
<p>Create a new project folder for your package and navigate into the folder. Then, run the following command in your terminal:</p>
<pre><code class="lang-json">git init
</code></pre>
<p>This will help you track the changes you make to your package. Also, make sure you have a remote version of your repository on GitHub (or your preferred hosting service).</p>
<h3 id="heading-3-initialize-npm-in-your-project">3. Initialize NPM in Your Project</h3>
<p>To do this, navigate to the root directory of your project and run the following command:</p>
<pre><code class="lang-json">npm init
</code></pre>
<p>This command will create a <code>package.json</code> file. You will get prompts to provide the following information:</p>
<ul>
<li><p><code>package-name</code>: As you learned earlier in this tutorial, the name of your package must be unique. Also it must be lowercase. It may include hyphens.</p>
</li>
<li><p><code>version</code>: The initial value is 1.0.0. You update the number when you update your package using <a target="_blank" href="https://www.freecodecamp.org/news/semantic-versioning-1fd6f57749f7/">semantic versioning</a>.</p>
</li>
<li><p><code>description</code>: You can provide a description of your package here. Indicate what your package does and how to use it.</p>
</li>
<li><p><code>entry point</code>: The entry file for your code. The default value is <code>index.js</code>.</p>
</li>
<li><p><code>test command</code>: Here, you can add the command you want to run when a user runs <code>npm run test</code>.</p>
</li>
<li><p><code>git repository</code>: The link to your remote repository on GitHub.</p>
</li>
<li><p><code>keywords</code>: Add relevant keywords that will help others find your package on the NPM registry.</p>
</li>
<li><p><code>author</code>: Add your name.</p>
</li>
<li><p><code>license</code>: You can add a license or use the default license (Internet Systems Consortium (ISC) License).</p>
</li>
</ul>
<p>See the screenshot below for an example of how to answer the prompt questions:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/npm-image1.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Creating a package.json file</em></p>
<p><em>Note: I left the</em> <code>test command</code> blank because there is no test command for the package in this tutorial.</p>
<h3 id="heading-4-add-your-code">4. Add Your Code</h3>
<p>Now, you can go ahead and add the code for your package.</p>
<p>First, you need to create the file that will be loaded when your module is required by another application. For this tutorial, that will be the <code>index.js</code> file.</p>
<p>Inside the <code>index.js</code> file, add the code for your package.</p>
<p>For this tutorial, I will be creating a simple package called <code>first-hello-npm</code>. This package returns the string <code>"Hello NPM!"</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//index.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">helloNpm</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"hello NPM"</span>
}

<span class="hljs-built_in">module</span>.exports = helloNpm
</code></pre>
<p>After creating your function, you should export it like in the example above. That way, anyone who downloads your package can load and use it in their code.</p>
<p>If you have been following along, you should now have your package created. But before you publish, you need to test your package. Testing your package reduces the chances of publishing bugs to the NPM registry.</p>
<h2 id="heading-how-to-test-your-npm-package">How to Test Your NPM Package</h2>
<p>Testing ensures that your NPM package works as expected. There are many ways to test your package. In this tutorial, you will learn one of the simplest ways of testing.</p>
<p>First, navigate to the root of your <code>package</code> project. Then, run the following command:</p>
<pre><code class="lang-json">npm link
</code></pre>
<p>This will make your package available globally. And you can require the package in a different project to test it out.</p>
<p>Create a <code>test</code> folder. And inside that test folder, add a <code>script.js</code> file.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/npm-image2.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Example of a test folder with a script.js file</em></p>
<p>In the example above, the test folder contains only the <code>script.js</code> file. It does not yet contain the package. To add the package you created to your test folder, run the command below:</p>
<pre><code class="lang-json">npm link &lt;name-of-package&gt;
</code></pre>
<p>In the case of the test folder for this tutorial, I will run the following command:</p>
<pre><code class="lang-json">npm link first-hello-npm
</code></pre>
<p>This will create a <code>node-modules</code> folder. And it'll add all the files and folders from your package – see the screenshot below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/npm-image3.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In the <code>script.js</code> file, you can now require your package and use it for the test.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// test/script.js</span>

<span class="hljs-keyword">const</span> helloNpm = <span class="hljs-built_in">require</span>(<span class="hljs-string">'first-hello-npm'</span>)

<span class="hljs-built_in">console</span>.log(helloNpm())
</code></pre>
<p>The <code>first-hello-npm</code> package is expected to return the string <code>"hello NPM!"</code>. As you can see from the screenshot below, the package works as expected when I run the script.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/npm-image4.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Test result for first-hello-npm package</em></p>
<p>After testing your package and ensuring it works as expected, you can now publish it on the NPM registry.</p>
<h2 id="heading-how-to-publish-your-npm-package">How to Publish Your NPM Package</h2>
<p>To publish your package on the NPM registry, you need to have an account. If you don't have an account, visit the <a target="_blank" href="https://www.npmjs.com/signup">NPM sign up page</a> to create one.</p>
<p>After creating the account, open your terminal and run the following command in the root of your package:</p>
<pre><code class="lang-json">npm login
</code></pre>
<p>You will get a prompt to enter your <code>username</code> and <code>password</code>. If login is successful, you should see a message like this:</p>
<p><code>Logged in as &lt;your-username&gt; on https://registry.npmjs.org/.</code></p>
<p>You can now run the following command to publish your package on the NPM registry:</p>
<pre><code class="lang-json">npm publish
</code></pre>
<p>If all goes well, you should get results similar to the screenshot below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/npm-image7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Notice indicating that the package is published successfully.</em></p>
<p>If you have been following along, then congratulations! You just published your first NPM package.</p>
<p>You can visit the <a target="_blank" href="https://www.npmjs.com/">NPM website</a> and run a search for your package. You should see your package show up in the search results.</p>
<p>For example, from the screenshot below, you can see the <code>first-hello-npm</code> package is now available on NPM.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/package-available.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The first-hello-npm package is now available on NPM</em></p>
<h2 id="heading-how-to-publish-scoped-npm-packages">How to Publish Scoped NPM Packages</h2>
<p>If an existing package has the same name you would like to use, the workaround is to publish a scoped package.</p>
<p>When you publish a scoped package, you have the option to make it public or private. If it's private, you can choose who you want to share the package with.</p>
<h3 id="heading-how-to-create-a-scoped-npm-package">How to Create a Scoped NPM Package</h3>
<p>To create a scoped package, first navigate to the root of your package directory.</p>
<p>Then, run the <code>npm init</code> command and pass your <code>username</code> as the value to the <code>scope</code> flag:</p>
<pre><code class="lang-json">npm init --scope=@your-username
</code></pre>
<p>Respond to the prompts to create a <code>package.json</code> file. For your package name, the format should be <code>@your-username/package-name</code>.</p>
<p>For example <code>@benjaminsemah/first-hello-npm</code>.</p>
<p>You can now add the code for your package and test it. The process is the same as already explained above.</p>
<p>Then, to publish your scoped package, run the following command in your terminal.</p>
<pre><code class="lang-json">npm publish --access public
</code></pre>
<p>You can change from <code>public</code> to <code>private</code> if you don't want to make the package available for public use.</p>
<p>You should see a response similar to this.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/scoped-package-published.PNG" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Scoped package published successfully.</em></p>
<p>Congratulations if you followed along. You've published your scoped package. You should see your scoped package on NPM if you search for it. For example in the screenshot below, you can see the scoped package I created in this tutorial.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/scoped-package-available.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Scoped package is now available on NPM</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Packages helps developers work faster. And they also improve collaboration. When you figure out a smarter way of doing things, one way you can share with the community is to create and publish your solution as a package.</p>
<p>In this article, you learned what packages are and why they are useful. You also learned how to create and publish packages on the NPM registry. The developer community awaits all the beautiful packages you will create and share.</p>
<p>Thanks for reading. And happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What Are Node Modules and How Do You Use Them? ]]>
                </title>
                <description>
                    <![CDATA[ Every Node.js application has modules. These modules form part of the building blocks of the application. They help developers work faster and write more structured code. In this tutorial, you will learn what node modules are. You will also learn abo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-node-modules/</link>
                <guid isPermaLink="false">66d45df0182810487e0ce11d</guid>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node ]]>
                    </category>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Tue, 06 Dec 2022 17:54:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/stock.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Every Node.js application has modules. These modules form part of the building blocks of the application. They help developers work faster and write more structured code.</p>
<p>In this tutorial, you will learn what node modules are. You will also learn about the three types of node modules. And we'll go over the right way to use them in your applications.</p>
<h2 id="heading-what-is-a-module-in-javascript">What is a Module in JavaScript?</h2>
<p>In simple terms, a module is a piece of reusable JavaScript code. It could be a <code>.js</code> file or a directory containing <code>.js</code> files. You can export the content of these files and use them in other files.</p>
<p>Modules help developers adhere to the DRY (Don't Repeat Yourself) principle in programming. They also help to break down complex logic into small, simple, and manageable chunks.</p>
<h2 id="heading-types-of-node-modules">Types of Node Modules</h2>
<p>There are three main types of Node modules that you will work with as a Node.js developer. They include the following.</p>
<ul>
<li><p>Built-in modules</p>
</li>
<li><p>Local modules</p>
</li>
<li><p>Third-party modules</p>
</li>
</ul>
<h3 id="heading-built-in-modules">Built-in Modules</h3>
<p>Node.js comes with some modules out of the box. These modules are available for use when you install Node.js. Some common examples of built-in Node modules are the following:</p>
<ul>
<li><p>http</p>
</li>
<li><p>url</p>
</li>
<li><p>path</p>
</li>
<li><p>fs</p>
</li>
<li><p>os</p>
</li>
</ul>
<p>You can use the built-in modules with the syntax below.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> someVariable = <span class="hljs-built_in">require</span>(<span class="hljs-string">'nameOfModule'</span>)
</code></pre>
<p>You load the module with the <code>require</code> function. You need to pass the name of the module you're loading as an argument to the <code>require</code> function.</p>
<p><strong>Note:</strong> The name of the module must be in quotation marks. Also, using <code>const</code> to declare the variable ensures that you do not overwrite the value when calling it.</p>
<p>You also need to save the returned value from the <code>require</code> function in <code>someVariable</code>. You can name that variable anything you want. But often, you will see programmers give the same to the variable as the name of the module (see example below).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> http = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http'</span>) 

server = http.createServer(<span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> { 
    res.writeHead(<span class="hljs-number">200</span>, {<span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/plain'</span>}) 
    res.end(<span class="hljs-string">'Hello World!'</span>)
})

server.listen(<span class="hljs-number">3000</span>)
</code></pre>
<p>You use the <code>require</code> function to load the built-in <code>http</code> module. Then, you save the returned value in a variable named <code>http</code>.</p>
<p>The returned value from the <code>http</code> module is an object. Since you've loaded it using the <code>require</code> function, you can now use it in your code. For example, call the <code>.createServer</code> property to create a server.</p>
<h3 id="heading-local-modules">Local Modules</h3>
<p>When you work with Node.js, you create local modules that you load and use in your program. Let's see how to do that.</p>
<p>Create a simple <code>sayHello</code> module. It takes a <code>userName</code> as a parameter and prints "hello" and the user's name.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">userName</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello <span class="hljs-subst">${userName}</span>!`</span>)
}

<span class="hljs-built_in">module</span>.exports = sayHello
</code></pre>
<p>First, you need to create the function. Then you export it using the syntax <code>module.exports</code>. It doesn't have to be a function, though. Your module can export an object, array, or any data type.</p>
<h4 id="heading-how-to-load-your-local-modules">How to load your local modules</h4>
<p>You can load your local modules and use them in other files. To do so, you use the <code>require</code> function as you did for the built-in modules.</p>
<p>But with your custom functions, you need to provide the path of the file as an argument. In this case, the path is <code>'./sayHello</code>' (which is referencing the <code>sayHello.js</code> file).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sayHello = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./sayHello'</span>)
sayHello(<span class="hljs-string">"Maria"</span>) <span class="hljs-comment">// Hello Maria!</span>
</code></pre>
<p>Once you've loaded your module, you can make a reference to it in your code.</p>
<h3 id="heading-third-party-modules">Third-Party Modules</h3>
<p>A cool thing about using modules in Node.js is that you can share them with others. The Node Package Manager (NPM) makes that possible. When you install Node.js, NPM comes along with it.</p>
<p>With NPM, you can share your modules as packages via <a target="_blank" href="https://www.npmjs.com/">the NPM registry.</a> And you can also use packages others have shared.</p>
<h4 id="heading-how-to-use-third-party-packages">How to use third-party packages</h4>
<p>To use a third-party package in your application, you first need to install it. You can run the command below to install a package.</p>
<pre><code class="lang-javascript">npm install &lt;name-<span class="hljs-keyword">of</span>-package&gt;
</code></pre>
<p>For example, there's a package called <code>capitalize</code>. It performs functions like capitalizing the first letter of a word.</p>
<p>Running the command below will install the capitalize package:</p>
<pre><code class="lang-javascript">npm install capitalize
</code></pre>
<p>To use the installed package, you need to load it with the <code>require</code> function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> capitalize = <span class="hljs-built_in">require</span>(<span class="hljs-string">'capitalize)</span>
</code></pre>
<p>And then you can use it in your code, like this for example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> capitalize = <span class="hljs-built_in">require</span>(<span class="hljs-string">'capitalize'</span>)
<span class="hljs-built_in">console</span>.log(capitalize(<span class="hljs-string">"hello"</span>)) <span class="hljs-comment">// Hello</span>
</code></pre>
<p>This is a simple example. But there are packages that perform more complex tasks and can save you loads of time.</p>
<p>For example, you can use the Express.js package which is a Node.js framework. It makes building apps faster and simple. To learn more about NPM, read this <a target="_blank" href="https://www.freecodecamp.org/news/what-is-npm-a-node-package-manager-tutorial-for-beginners/">freeCodeCamp article on the Node Package Manager</a>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned about what Node modules are and the three types of node modules. You also learned about how to use the different types in your application.</p>
<p>Thanks for reading. And happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ module.exports – How to Export in Node.js and JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Dillion Megida In programming, modules are components of a program with one or more functions or values.  These values can also be shared across the entire program and can be used in different ways. In this article, I will show you how to share fu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/module-exports-how-to-export-in-node-js-and-javascript/</link>
                <guid isPermaLink="false">66d84f4639c4dccc43d4d48e</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ node js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 25 Apr 2022 21:03:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/pexels-conrad-marshall-615670.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dillion Megida</p>
<p>In programming, modules are components of a program with one or more functions or values. </p>
<p>These values can also be shared across the entire program and can be used in different ways.</p>
<p>In this article, I will show you how to share functions and values by exporting and importing modules in Node.js.</p>
<h2 id="heading-why-export-modules">Why Export Modules?</h2>
<p>You'll want to export modules so that you can use them in other parts of your application. </p>
<p>Modules can serve different purposes. They can provide simple utilities to modify strings. They can provide methods for making API requests. Or they can even provide constants and primitive values.</p>
<p>When you export a module, you can import it into other parts of your applications and consume it.</p>
<p>Node.js supports <a target="_blank" href="https://nodejs.org/api/modules.html">CommonJS Modules</a> and <a target="_blank" href="https://nodejs.org/api/esm.html">ECMAScript Modules</a>.</p>
<p>For the rest of this article, we'll focus on CommonJS Modules, the original approach to packaging modules in Node.js.</p>
<p>If you want to learn more about ES Modules (along with CommonJS modules), you can <a target="_blank" href="https://www.freecodecamp.org/news/modules-in-javascript/">check out this in-depth guide</a>.</p>
<h2 id="heading-how-to-export-modules-in-node">How to Export Modules in Node</h2>
<p>Node.js already exports in-built modules which include <a target="_blank" href="https://nodejs.dev/learn/the-nodejs-fs-module">fs</a>, <a target="_blank" href="https://nodejs.dev/learn/the-nodejs-path-module">path</a>, and <a target="_blank" href="https://nodejs.dev/learn/the-nodejs-http-module">http</a> to name a few. But you can create your own modules.</p>
<p>Node.js treats each file in a Node project as a module that can export values and functions from the file.</p>
<p>Say, for example, that you have a utility file <code>utility.js</code> with the following code:</p>
<pre><code class="lang-js"><span class="hljs-comment">// utility.js</span>

<span class="hljs-keyword">const</span> replaceStr = <span class="hljs-function">(<span class="hljs-params">str, char, replacer</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> regex = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(char, <span class="hljs-string">"g"</span>)
  <span class="hljs-keyword">const</span> replaced = str.replace(regex, replacer)
  <span class="hljs-keyword">return</span> replaced
}
</code></pre>
<p><code>utility.js</code> is a module which other files can import things from. But <code>utility.js</code> currently does not export anything. </p>
<p>You can verify this by examining the global <code>module</code> object in each file. When you print the <code>module</code> global object in this utility file, you have:</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">module</span>)

<span class="hljs-comment">// {</span>
<span class="hljs-comment">//   id: ".",</span>
<span class="hljs-comment">//   path: "...",</span>
<span class="hljs-comment">//   exports: {},</span>
<span class="hljs-comment">//   parent: null,</span>
<span class="hljs-comment">//   filename: "...",</span>
<span class="hljs-comment">//   loaded: false,</span>
<span class="hljs-comment">//   children: [],</span>
<span class="hljs-comment">//   paths: [</span>
<span class="hljs-comment">//     ...</span>
<span class="hljs-comment">//   ],</span>
<span class="hljs-comment">// }</span>
</code></pre>
<p>The <code>module</code> object has an <code>exports</code> property which, as you can see, is an empty object. </p>
<p>So any attempt to import anything from this file will throw an error.</p>
<p>The <code>utility.js</code> file has a <code>replaceStr</code> method which replaces characters in a string with some other characters. We can export this function from this module to be used by other files.</p>
<p>Here's how:</p>
<pre><code class="lang-js"><span class="hljs-comment">// utility.js</span>

<span class="hljs-keyword">const</span> replaceStr = <span class="hljs-function">(<span class="hljs-params">str, char, replacer</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> regex = <span class="hljs-keyword">new</span> <span class="hljs-built_in">RegExp</span>(char, <span class="hljs-string">"g"</span>)
  <span class="hljs-keyword">const</span> replaced = str.replace(regex, replacer)
  <span class="hljs-keyword">return</span> replaced
}

<span class="hljs-built_in">module</span>.exports = { replaceStr }
<span class="hljs-comment">// or</span>
<span class="hljs-built_in">exports</span>.replaceStr = replaceStr
</code></pre>
<p>Now, <code>replaceStr</code> is available for use in other parts of the application. To use it, you import it like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> { replaceStr } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./utility.js'</span>)

<span class="hljs-comment">// then use the function anywhere</span>
</code></pre>
<h2 id="heading-moduleexports-vs-exports-in-node">module.exports vs exports in Node</h2>
<p>You can export functions and values from a module by either using <code>module.exports</code>:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = { value1, function1 }
</code></pre>
<p>or by using <code>exports</code>:</p>
<pre><code class="lang-js"><span class="hljs-built_in">exports</span>.value1 = value1
<span class="hljs-built_in">exports</span>.function1 = function1
</code></pre>
<p>What's the difference?</p>
<p>These methods are pretty identical. Basically, <code>exports</code> serves as a reference to <code>module.exports</code>. To understand this better, let's populate the <code>exports</code> object by using the two ways of exporting values:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> value1 = <span class="hljs-number">50</span>
<span class="hljs-built_in">exports</span>.value1 = value1

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">module</span>)
<span class="hljs-comment">// {</span>
<span class="hljs-comment">//   id: ".",</span>
<span class="hljs-comment">//   path: "...",</span>
<span class="hljs-comment">//   exports: { value1: 50 },</span>
<span class="hljs-comment">//   parent: null,</span>
<span class="hljs-comment">//   filename: "...",</span>
<span class="hljs-comment">//   loaded: false,</span>
<span class="hljs-comment">//   children: [],</span>
<span class="hljs-comment">//   paths: [</span>
<span class="hljs-comment">//     ...</span>
<span class="hljs-comment">//   ],</span>
<span class="hljs-comment">// }</span>

<span class="hljs-keyword">const</span> function1 = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I am a function"</span>)
}
<span class="hljs-built_in">module</span>.exports = { function1, ...module.exports }

<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">module</span>)

<span class="hljs-comment">// {</span>
<span class="hljs-comment">//   id: ".",</span>
<span class="hljs-comment">//   path: "...",</span>
<span class="hljs-comment">//   exports: { function1: [Function: function1] },</span>
<span class="hljs-comment">//   parent: null,</span>
<span class="hljs-comment">//   filename: "...",</span>
<span class="hljs-comment">//   loaded: false,</span>
<span class="hljs-comment">//   children: [],</span>
<span class="hljs-comment">//   paths: [</span>
<span class="hljs-comment">//     ...</span>
<span class="hljs-comment">//   ],</span>
<span class="hljs-comment">// }</span>
</code></pre>
<p>There are two things to notice here:</p>
<ul>
<li>The <code>exports</code> keyword is a reference to the <code>exports</code> object in the <code>modules</code> object. By doing <code>exports.value1 = value1</code>, it added the <code>value1</code> property to the <code>module.exports</code> object, as you can see in the first log.</li>
<li>The second log does not contain the <code>value1</code> export anymore. It only has the function exported using <code>module.exports</code>. Why is this so?</li>
</ul>
<p><code>module.exports = ...</code> is a way of reassigning a new object to the <code>exports</code> property. The new object only contains the function, so the <code>value1</code> is no longer exported.</p>
<p>So what's the difference?</p>
<p>Exporting values with just the <code>exports</code> keyword is a quick way to export values from a module. You can use this keyword at the top or bottom, and all it does is populate the <code>module.exports</code> object. But if you're using <code>exports</code> in a file, stick to using it throughout that file.</p>
<p>Using <code>module.exports</code> is a way of explicitly specifying a module's exports. And this should ideally only exist once in a file. If it exists twice, the second declaration reassigns the <code>module.exports</code> property, and the module only exports what the second declaration states.</p>
<p>So as a solution to the previous code, you either export like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ...</span>
<span class="hljs-built_in">exports</span>.value1 = value1

<span class="hljs-comment">// ...</span>
<span class="hljs-built_in">exports</span>.function1 = function1
</code></pre>
<p>or like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// ...</span>
<span class="hljs-built_in">module</span>.exports = { value1, function1 }
</code></pre>
<h2 id="heading-wrap-up">Wrap up</h2>
<p>Each file in a Node.js project is treated as a module that can export values to be used by other modules. </p>
<p><code>module.exports</code> is an object in a Node.js file that holds the exported values and functions from that module.</p>
<p>Declaring a <code>module.exports</code> object in a file specifies the values to be exported from that file. When exported, another module can import this values with the <code>require</code> global method.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Bypass ES Modules Errors in Next.js with Dynamic Imports ]]>
                </title>
                <description>
                    <![CDATA[ By Caleb Olojo When you are building an application that can be accessed on the web, there are a lot of dependencies or packages that you will need for your application to function well. You'll need most of these packages when you're building JAMStac... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-bypass-es-modules-error-in-next-js/</link>
                <guid isPermaLink="false">66d45ddd8812486a37369c7b</guid>
                
                    <category>
                        <![CDATA[ error handling ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 19 Apr 2022 19:58:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/tim-gouw-1K9T5YiZ2WU-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Caleb Olojo</p>
<p>When you are building an application that can be accessed on the web, there are a lot of dependencies or packages that you will need for your application to function well.</p>
<p>You'll need most of these packages when you're building JAMStack applications with frameworks or libraries like React, Vuejs, Next.js, or Angular.</p>
<p>In this article, I'll walk you through an error you may get when you are building JavaScript apps with Next.js, and how to bypass it.</p>
<h2 id="heading-what-the-heck-are-esmodules">What the Heck are ESModules?</h2>
<p>ESModules are the ECMAScript standards for working with JavaScript modules in the browser.</p>
<p>"What does that have to do with these annoying and frustrating errors that I have been seeing for the past few days?" you might ask me.</p>
<p>Well... Node.js has been using the <strong>CommonJS</strong> standards for a very long time to properly structure JavaScript code or modules in this scenario, and the majority of the code we write resides/works in the browser.</p>
<p>There were no standards to properly guide how JavaScript modules were used, or interpreted, at least in web browsers. This challenge brought about the ESModules standards which guide how JavaScript modules work in the browser.</p>
<p>This standard was approved when ES6 (ECMAScript 6) was launched in 2015, and brought about the implementation of the standards in various web browsers like Chrome, Safari, Firefox, and Microsoft's Edge.</p>
<p>Most of the packages we use in building frontend UIs are written in JavaScript. They have modules that are exporting a particular function (it could be a JavaScript component), an object, a string, a bunch of arrays, and so on.</p>
<p>These functions, arrays, or strings can be exposed as libraries to other JavaScript files. Say, for example, we have a function that prints the name of anyone in the console. The syntax will be like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// name.js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> (name) =&gt; <span class="hljs-built_in">console</span>.log(name)
</code></pre>
<p>The snippet above describes a default export, without a specific name. This means that if we want to use the function in this module, we can call it any name, since a name wasn't explicitly assigned to it upon declaration</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> printName <span class="hljs-keyword">from</span> <span class="hljs-string">"./name.js"</span>

printName(<span class="hljs-string">"Dodo"</span>)
</code></pre>
<h2 id="heading-okay-why-do-i-still-get-the-error-though">Okay, why do I still get the error though?</h2>
<p>Yes. Now on to that error. When we begin to interface with a lot of dependencies or packages in our applications, some things might start going wrong if we don't give proper care to our codebases.</p>
<p>We start to deal with versioning of these packages, breaking changes, and releases sometimes, which we can not keep track of. Then, we might begin to scurry down the rabbit hole of downgrading or upgrading a particular npm package before anything even works at all.</p>
<p>Most of these errors may arise from the maintainers of these packages. Take, for example, the ESModules standard – which is relatively new – that we are discussing in this article. It may take some time for it to be adopted by some frameworks or front-end JavaScript libraries out there, for example, Next.js.</p>
<p>The error in the image below shows that we can't use the CommonJS approach to import a module.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/serialize-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This new standard and the fact that it's a bit unfamiliar to these tools we use is the reason for this error. <a target="_blank" href="https://www.smashingmagazine.com/2021/11/maintain-large-nextjs-application/">Nirmalya Ghosh wrote this piece on how to maintain large Next.js apps</a>, you should take a look at it.</p>
<h2 id="heading-how-to-use-nextjs-dynamic-imports">How to use Next.js dynamic imports</h2>
<p>Now that we've gone through the rudiments of what ESModules are, let's see how we can fix the error that is quite similar to the one we saw in the image above. We'll see how we can fix it with dynamic imports in Next.js.</p>
<p>I'll be assuming you already have a Next.js app running, so I'll just share the corresponding ESModule error I got from my terminal in the code block below:</p>
<pre><code class="lang-bash">Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /path/to/package

require() of ES modules is not supported. 

ES module file as it is a .js file whose nearest parent package.json contains <span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span> <span class="hljs-built_in">which</span> defines all .js files <span class="hljs-keyword">in</span> that package scope as ES modules.

Instead rename index.js to end <span class="hljs-keyword">in</span> .cjs, change the requiring code to use import(), or remove <span class="hljs-string">"type"</span>: <span class="hljs-string">"module"</span> from /path/to/package
</code></pre>
<p>Take a look at the error above so that you're quite familiar with it. Once you've done that, let's proceed.</p>
<h3 id="heading-what-are-dynamic-imports">What are dynamic imports?</h3>
<p>Dynamic imports is a feature of Next.js that allows you to work with JavaScript modules conveniently in the browser.</p>
<p>It provides a means of pre-rendering these modules with SSR (Server-side Rendering) so that users do not need to send requests continuously to the server when they need — say, for example — a page that uses a JavaScript module. With dynamic imports, the modules are already pre-rendered in the browser.</p>
<p>Recently, I was working on a project that had to do with markdown content. I needed to use rehype plugins, but I kept on getting the error in the previous code block.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> rehypeSlug = dynamic(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'rehype-slug'</span>), { <span class="hljs-attr">ssr</span>: <span class="hljs-literal">false</span> })
<span class="hljs-keyword">const</span> rehypeCodeTitles = dynamic(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'rehype-code-titles'</span>), {
  <span class="hljs-attr">ssr</span>: <span class="hljs-literal">false</span>,
})
<span class="hljs-keyword">const</span> rehypeAutolinkHeadings = dynamic(
  <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'rehype-autolink-headings'</span>),
  { <span class="hljs-attr">ssr</span>: <span class="hljs-literal">false</span> }
)
<span class="hljs-keyword">const</span> rehypePrism = dynamic(<span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">import</span>(<span class="hljs-string">'rehype-prism-plus'</span>), { <span class="hljs-attr">ssr</span>: <span class="hljs-literal">false</span> })
</code></pre>
<p>The snippet above shows how you can import a module with dynamic imports and pass the <code>ssr</code> object as an argument to it.</p>
<p>With this approach of using dynamic imports, the ESModule errors that kept on showing up were removed.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>So I hope you'll be able to make use of this feature, and I hope it liberates you from that error. </p>
<p>There's a lot you have to think about when you're building JavaScript applications, so this can be one less thing. Thank you for reading this article, and I hope you enjoyed it.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Modules in JavaScript – CommonJS and ESmodules Explained ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article we're going to take a look at modules in JavaScript. Modules are a technique heavily used in today's software design/architecture. First we're going to learn what they are and the different types of modules that exist. Th... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/modules-in-javascript/</link>
                <guid isPermaLink="false">66d45f13d1ffc3d3eb89ddf3</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Thu, 14 Apr 2022 01:17:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/carson-arias-7Z03R1wOdmI-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article we're going to take a look at modules in JavaScript.</p>
<p>Modules are a technique heavily used in today's software design/architecture.</p>
<p>First we're going to learn what they are and the different types of modules that exist. Then we're going to discuss why modules are useful. Then we're going to see examples and basic syntax for the most used module types, and finally we're going to discuss bundling, why is it necessary, and how to do it.</p>
<p>Enough cháchara, let's go! =D</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-are-modules-and-why-are-they-useful">What are modules and why are they useful</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-modules">Types of modules</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-commonjs-modules">CommonJS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-esmodules">ESmodules</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-using-modules">Using modules</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-bundling-modules">Bundling modules</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-roundup">Roundup</a></p>
</li>
</ul>
<h1 id="heading-what-are-modules-and-why-are-they-useful">What are modules and why are they useful</h1>
<p>A module is just a piece of code in a file that you can call and use from other files. A modular design is the opposite of having all your project's code in one single file.</p>
<p>When developing a big project, it's very useful to divide our code into modules for the following reasons:</p>
<ul>
<li><p>It's good for dividing concerns and features into different files, which helps visualization and organization of code.</p>
</li>
<li><p>Code tends to be easier to maintain and less prone to errors and bugs when it's clearly organized.</p>
</li>
<li><p>Modules can be easily used and reused in different files and parts of our project, without needing to rewrite the same code again.</p>
</li>
</ul>
<p>Instead of having all of our program's components in a single file, we can divide it into parts or modules, and make each of them responsible for a single feature/concern.</p>
<p>If this concept isn't clear enough now, don't worry. We'll see some examples in a sec.</p>
<h1 id="heading-types-of-modules">Types of modules</h1>
<p>As with almost everything in life, and especially in JavaScript, there are many ways for us to implement modules.</p>
<p>As JavaScript was first created to be just a small scripting language for websites, a feature for big projects like modules wasn't supported at the beginning.</p>
<p>But as the language and the ecosystem grew, developers started to see the need for this feature. And so different options and libraries were developed to add this feature to JavaScript.</p>
<p>Of the many available, we're only going to take a look at CommonJS and ESmodules, which are the most recent and widely used ones.</p>
<p>Side comment: Did you know that <a target="_blank" href="https://thenewstack.io/brendan-eich-on-creating-javascript-in-10-days-and-what-hed-do-differently-today/">Javascript was originally created in just 10 days of work</a>?</p>
<p>When analyzing the complexities of JavaScript and understanding how the language has evolved, I think it's important to have in mind that the language wasn't originally created to do what it does nowadays. It's the growth of the Javascript ecosystem that pushed for many of the changes that have come about.</p>
<h2 id="heading-commonjs-modules">CommonJS modules</h2>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/CommonJS">CommonJS</a> is a set of standards used to implement modules on JavaScript. The project was started by Mozilla engineer Kevin Dangoor in 2009.</p>
<p>CommonJS is mainly used in server-side JS apps with Node, as browsers don't support the use of CommonJS.</p>
<p>As a side comment, Node used to only support CommonJS to implement modules, but nowadays it also supports ESmodules which is a more modern approach.</p>
<p>So let's see how CommonJS looks in actual code.</p>
<p>To implement modules, you need a Node app on your computer first. So create one by running <code>npm init -y</code>.</p>
<p>First let's create a <code>main.js</code> file with a simple function in it.</p>
<pre><code class="lang-plaintext">const testFunction = () =&gt; {
    console.log('Im the main function')
}

testFunction()
</code></pre>
<p>Ok now let's say we want to have another function called from our main file, but we don't want the function in it as it's not part of our core feature. For this, let's create a <code>mod1.js</code> file and add this code to it:</p>
<pre><code class="lang-plaintext">const mod1Function = () =&gt; console.log('Mod1 is alive!')
module.exports = mod1Function
</code></pre>
<p><code>module.exports</code> is the keyword we use to declare all we want to export from that file.</p>
<p>To use this function in our <code>main.js</code> file, we can do it like this:</p>
<pre><code class="lang-plaintext">mod1Function = require('./mod1.js')

const testFunction = () =&gt; {
    console.log('Im the main function')
    mod1Function()
}

testFunction()
</code></pre>
<p>See that we declare whatever we want to use and then assign that to the <code>require</code> of the file we want to use. Piece of cake. ;)</p>
<p>If we wanted to export more than one thing from a single module, we can do it like this:</p>
<pre><code class="lang-plaintext">const mod1Function = () =&gt; console.log('Mod1 is alive!')
const mod1Function2 = () =&gt; console.log('Mod1 is rolling, baby!')

module.exports = { mod1Function, mod1Function2 }
</code></pre>
<p>And on the main.js file we can use both functions like this:</p>
<pre><code class="lang-plaintext">({ mod1Function, mod1Function2 } = require('./mod1.js'))

const testFunction = () =&gt; {
    console.log('Im the main function')
    mod1Function()
    mod1Function2()
}

testFunction()
</code></pre>
<p>And that's pretty much it. Quite simple, right? It is simple but it's a powerful tool to use. =)</p>
<h2 id="heading-esmodules">ESmodules</h2>
<p>Now let's review ESmodules. ESmodules is a standard that was introduced with ES6 (2015). The idea was to standarize how JS modules work and implement this features in browsers (which didn't previously support modules).</p>
<p>ESmodules is a more modern approach that is currently supported by browser and server-side apps with Node.</p>
<p>Let's see this in code. Once again we start by creating a Node app with <code>npm init -y</code>.</p>
<p>Now we go to our <code>package.json</code> and add <code>"type": "module"</code> to it, like this:</p>
<pre><code class="lang-plaintext">{
  "name": "modulestestapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "module"
}
</code></pre>
<p>If we don't do this and try to implement ESmodules on Node, we'll get an error like this:</p>
<pre><code class="lang-plaintext">(node:29568) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
...
SyntaxError: Cannot use import statement outside a module
</code></pre>
<p>Now let's repeat the exact same example. In our <code>main.js</code> file we'll have the following code:</p>
<pre><code class="lang-plaintext">// main.js
import { mod1Function } from './mod1.js'

const testFunction = () =&gt; {
    console.log('Im the main function')
    mod1Function()
}

testFunction()
</code></pre>
<p>And on <code>mod1.js</code> we'll have this:</p>
<pre><code class="lang-plaintext">// mod1.js
const mod1Function = () =&gt; console.log('Mod1 is alive!')
export { mod1Function }
</code></pre>
<p>Notice instead of <code>require</code> we're using <code>import</code> and instead of <code>module.exports</code> we're using <code>export</code>. The syntaxt is a bit different but the behaviour is very similar.</p>
<p>Again if we wanted to export more than one thing from the same file we could do it like this:</p>
<pre><code class="lang-plaintext">// main.js
import { mod1Function, mod1Function2 } from './mod1.js'

const testFunction = () =&gt; {
    console.log('Im the main function')
    mod1Function()
    mod1Function2()
}

testFunction()
</code></pre>
<pre><code class="lang-plaintext">// mod1.js
const mod1Function = () =&gt; console.log('Mod1 is alive!')
const mod1Function2 = () =&gt; console.log('Mod1 is rolling, baby!')

export { mod1Function, mod1Function2 }
</code></pre>
<p>Another feature available in ESmodules is import renaming, which can be done like this:</p>
<pre><code class="lang-plaintext">// main.js
import { mod1Function as funct1, mod1Function2 as funct2 } from './mod1.js'

const testFunction = () =&gt; {
    console.log('Im the main function')
    funct1()
    funct2()
}

testFunction()
</code></pre>
<p>Notice we use the <code>as</code> keyword after each function, and then rename it however we want. Later in our code, we can use that new name instead of the original name the import has. ;)</p>
<p>Another thing you could do is import all exports together and put them together in an object, like this:</p>
<pre><code class="lang-plaintext">// main.js
import * as mod1 from './mod1.js' 

const testFunction = () =&gt; {
    console.log('Im the main function')
    mod1.mod1Function()
    mod1.mod1Function2()
}

testFunction()
</code></pre>
<p>This may be useful in cases when, throughout our code, we want to be explicit about where each import is coming from. See that functions are now being called like <code>mod1.mod1Function()</code>.</p>
<p>The last thing worth mentioning is the <code>default</code> keyword. With it we can set a default export for a given module. Like this:</p>
<pre><code class="lang-plaintext">// mod1.js
const mod1Function = () =&gt; console.log('Mod1 is alive!')
const mod1Function2 = () =&gt; console.log('Mod1 is rolling, baby!')

export default mod1Function
export { mod1Function2 }
</code></pre>
<p>And what does it mean to have a default export? Well, it means we don't have to destructure it when we import it. We can use it just like this:</p>
<pre><code class="lang-plaintext">// main.js
import mod1Function, { mod1Function2 } from './mod1.js' 

const testFunction = () =&gt; {
    console.log('Im the main function')
    mod1Function()
    mod1Function2()
}

testFunction()
</code></pre>
<p>We can even rename the import whatever we want without the <code>as</code> keyword, since JavaScript "knows" that if we're not destructuring we'll be referring to the default import.</p>
<pre><code class="lang-plaintext">// main.js
import lalala, { mod1Function2 } from './mod1.js' 

const testFunction = () =&gt; {
    console.log('Im the main function')
    lalala()
    mod1Function2()
}

testFunction()
</code></pre>
<p>And that pretty much sums it up about ESmodules too. Straightforward I hope. =)</p>
<h1 id="heading-using-modules">Using modules</h1>
<p>Ok now that we're clear about the different types of modules available and how they work, let's see how we can implement modules in a website using HMTL and Vanilla JS.</p>
<p>Let's create a simple HTML file with a heading, two buttons, and a script tag linking to our <code>main.js</code> file.</p>
<pre><code class="lang-plaintext">&lt;!-- index.html --&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Document&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;I'm just a test...&lt;/h1&gt;
    &lt;button id="isAlive"&gt;Is mod1 alive?&lt;/button&gt;
    &lt;button id="isRolling"&gt;Is mod1 rolling?&lt;/button&gt;
    &lt;script src="./main.js" type="module"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Pay attention to the fact that I'm declaring <code>type="module"</code> on the script tag. We need to do this in order to use the JS module feature. If we don't, we'll get an error like this:</p>
<pre><code class="lang-plaintext">Uncaught SyntaxError: Cannot use import statement outside a module
</code></pre>
<p>If we open our HTML file we should get something like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/screenshot-2.png" alt="screenshot-2" width="600" height="400" loading="lazy"></p>
<p>Our <code>main.js</code> file will have this code:</p>
<pre><code class="lang-plaintext">// main.js
import { mod1Function, mod1Function2 } from './mod1.js'

const testFunction = () =&gt; console.log('Im the main function')

document.getElementById('isAlive').addEventListener('click', () =&gt; mod1Function())
document.getElementById('isRolling').addEventListener('click', () =&gt; mod1Function2())

testFunction()
</code></pre>
<p>We're just adding a click event listener to each button so the functions that come from the <code>mod1.js</code> file get executed.</p>
<p>Ok so now we can serve our HTML file and see if this works. We need to serve the file, we can't just open the HTML in the browser because we would get a CORS error like this:</p>
<pre><code class="lang-plaintext">Access to script at ... from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, brave, chrome-untrusted, https.
</code></pre>
<p>To serve it quickly you can use the <strong>Live server</strong> VS code extension, or create a Node app by running <code>npm init -y</code> and then running <code>npx serve</code>.</p>
<p>Anyway, once the file is served we can click on each button and test that our functions execute correctly. Our console should look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/screenshot_1-1.png" alt="screenshot_1-1" width="600" height="400" loading="lazy"></p>
<p>But there's one more thing about this. If we go to the network tab of the browser's developer tools, and filter by JS files, we can see that the website is loading two files, <code>main.js</code> and <code>mod1.js</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/screenshot_3.png" alt="screenshot_3" width="600" height="400" loading="lazy"></p>
<p>Of course if we're going to use the code inside each file, both need to be loaded – but this is not the best thing to do. That's because the browser needs to perform two different requests to load all the JS necessary.</p>
<p>We should always try to reduce the requests to the minimun to increase the performance of our projects. So let's see how we can do this with the help of a module bundler.</p>
<p>Side comment: if you'd like a video explanation, <a target="_blank" href="https://egghead.io/lessons/javascript-use-javascript-modules-in-the-browser">Kent C Dodds has a great one</a>. I really recommend that you follow him, he's one of the best JS teachers out there. And <a target="_blank" href="https://www.youtube.com/watch?v=qgRUr-YUk1Q">here's another cool video</a> by Fireship. ;)</p>
<h1 id="heading-bundling-modules">Bundling modules</h1>
<p>As previously mentioned, dividing our code into modules is nice because our codebase will be more organized and it will be easier to reuse our code.</p>
<p>But these are advantages only for the development phase of a project. When in production, modules are not the best thing, as forcing the browser to make a request for each JS file might hurt the site's performance.</p>
<p>This problem can be easily solved with the use of a module bundler. Simply put, module bundlers are programs that take JS modules as input and combine them into a single file (many module bundlers have many more features but that's their core concept).</p>
<p>Thanks to this, as developers we can code our project dividing it into nicely organized pieces, and then run a module bundler to obtain the final code that will be used in production.</p>
<p>This step of converting "development code" to "production code" is normally recognized as "build".</p>
<p>There're many options to use for this (like <a target="_blank" href="https://browserify.org/">Browserify</a>, <a target="_blank" href="https://parceljs.org/">Parcel</a>, <a target="_blank" href="https://rollupjs.org/guide/en/">Rollup.js</a>, <a target="_blank" href="https://www.snowpack.dev/">Snowpack</a>...) but the most widely used is <a target="_blank" href="https://webpack.js.org/">Webpack</a>. So let's see an example using Webpack.</p>
<ul>
<li><p>Side comment 1: If you want to dig deeper into module bundlers and how they work, <a target="_blank" href="https://www.youtube.com/watch?v=5IG4UmULyoA&amp;t=382s">this awesome video by Fireship</a> might be a good place to start.</p>
</li>
<li><p>Side comment 2: Webpack is a very robust and sophisticated tool that can do many things besides bundling JS files. Check out <a target="_blank" href="https://webpack.js.org/">their docs</a> if you want to learn more.</p>
</li>
</ul>
<p>Great, so now we can start off by creating a Node app (if you haven't already) by running <code>npm init -y</code>. Then we'll need to install Webpack and the Webpack CLI by running <code>npm i --save-dev webpack webpack-cli</code>.</p>
<p>Next we'll create a <code>webpack.config.js</code> file and put this code inside it:</p>
<pre><code class="lang-plaintext">/* webpack.config.js */
const path = require('path');

module.exports = {
  entry: './main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
};
</code></pre>
<p>This file will be responsible for the configuration of Webpack and how it will work in our app.</p>
<p>What we're doing here first is setting the entry file (<code>entry: './main.js'</code>). Webpack will start by reading that file and then analyzing all the dependencies (modules imported from that file). In other words, the entry file is our main JS file where all other modules are imported.</p>
<p>Then we're declaring the output – first declaring the path where it will be stored and then declaring the name of the bundled file.</p>
<pre><code class="lang-plaintext">output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
},
</code></pre>
<p>Super! Now let's go to our <code>package.json</code> file and add a <code>build</code> script, like this:</p>
<pre><code class="lang-plaintext">{
  "name": "testappv2",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1",
    "build": "webpack"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^5.72.0",
    "webpack-cli": "^4.9.2"
  }
}
</code></pre>
<p>Then we can go back to our terminal and run <code>npm run build</code>. That should create a <code>dist</code> directory within our project, and inside it a <code>bundle.js</code> file.</p>
<p>If you check that file out, you'll see this code within it:</p>
<pre><code class="lang-plaintext">(()=&gt;{"use strict";document.getElementById("isAlive").addEventListener("click",(()=&gt;console.log("Mod1 is alive!"))),document.getElementById("isRolling").addEventListener("click",(()=&gt;console.log("Mod1 is rolling, baby!"))),console.log("Im the main function")})();
</code></pre>
<p>You'll see that it's practically the same code we had distributed in our files, but all bundled in a single file and minified.</p>
<p>The only thing left is to change the script tag in our <code>index.html</code> file so it consumes the bundled JS now, like this:</p>
<pre><code class="lang-plaintext">&lt;!-- index.html --&gt;
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Document&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;I'm just a test...&lt;/h1&gt;
    &lt;button id="isAlive"&gt;Is mod1 alive?&lt;/button&gt;
    &lt;button id="isRolling"&gt;Is mod1 rolling?&lt;/button&gt;
    &lt;script src="./dist/bundle.js" type="module"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Now we can serve it again, check that the JS still works perfectly, and if we open the network tab again we should see just a single file being loaded! =D</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/screenshot_2-1.png" alt="screenshot_2-1" width="600" height="400" loading="lazy"></p>
<p>I hope this simple example helped you understand the relevance of module bundlers and how they help us combine the great development experience of modular architecture with good site performance.</p>
<h1 id="heading-roundup">Roundup</h1>
<p>Well, we're done for today. In this article we've seen what modules are, why are they cool, the different ways you can implement modules in JavaScript, and a practical example of bundling our code with Webpack.</p>
<p>For a complete guide on JS modules, you can take a look <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules">at this article</a>.</p>
<p>As always, I hope you enjoyed the article and learned something new. If you want, you can also follow me on <a target="_blank" href="https://www.linkedin.com/in/germancocca/">linkedin</a> or <a target="_blank" href="https://twitter.com/CoccaGerman">twitter</a>.</p>
<p>Cheers and see you in the next one! =D</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/giphy.gif" alt="giphy" width="600" height="400" loading="lazy"></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Modules – A Beginner's Guide ]]>
                </title>
                <description>
                    <![CDATA[ By Madison Kanna JavaScript modules (also known as ES modules or ECMAScript modules) were created to help make JavaScript code more organized and maintainable. Understanding how ES modules work will help you become a better JavaScript developer. In t... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-modules-beginners-guide/</link>
                <guid isPermaLink="false">66d8518e62a291dea89878de</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 15 Dec 2021 16:47:38 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/12/lego.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Madison Kanna</p>
<p>JavaScript modules (also known as ES modules or ECMAScript modules) were created to help make JavaScript code more organized and maintainable.</p>
<p>Understanding how ES modules work will help you become a better JavaScript developer. In this article, we'll cover:</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-a-module">What is a module?</a></li>
<li><a class="post-section-overview" href="#heading-what-are-es-modules-why-do-we-use-them">What are ES modules? Why do we use them?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-es-modules">How to use ES modules</a></li>
<li><a class="post-section-overview" href="#heading-other-module-systems-in-javascript">Other module systems used in JavaScript</a></li>
</ul>
<p>Let's get started.</p>
<h1 id="module">What is a module?</h1>

<p>A module in JavaScript is just a file of code. You can think of a module as a reusable and independent unit of code.</p>
<p>Modules are the building blocks of your codebase. As your application gets bigger, you can split your code up into multiple files, aka modules. </p>
<p>Using modules allows you to break down large programs into more manageable pieces of code. </p>
<h1 id="es-modules">What are ES modules? Why do we use them?</h1>

<p><strong>ES modules are the official module system used in JavaScript.</strong> There are other module systems that can be used in JavaScript as well, and we'll talk more about those later. But for now, know that we're learning about ES modules rather than other module systems because they're standard for modules in JavaScript. </p>
<p>As a JavaScript developer, you'll likely use ES modules in your daily work.</p>
<p>Here are some of the advantages that developers get from using ES modules:</p>
<ol>
<li><strong>Organization.</strong> By breaking down large programs into smaller pieces of related code, you keep your program organized.</li>
<li><strong>Reusability.</strong> With ES modules, you can write code in one place and reuse that code in other files throughout your codebase. For example, instead of rewriting the same function everywhere, you can write a function inside of one module and then import it into another file and use it there.</li>
</ol>
<p>Let’s dive into an example using ES modules. We'll learn about how ES modules work so you can use them in your projects going forward. As we work with ES modules, we’ll see each of the above advantages demonstrated. </p>
<h1 id="how-to-use">How to use ES Modules</h1>

<p>Let’s start out with creating a vanilla JavaScript <a target="_blank" href="https://replit.com/">Replit</a>. You can also find the completed code <a target="_blank" href="https://replit.com/@madisonkanna/ES-Modules">here</a>.  </p>
<p>Once on Replit, we can create a new project and choose HTML, CSS, and JavaScript. This will create a starter project that has an <code>index.html</code> file, a <code>script.js</code> file, and a <code>style.css</code> file. This is everything we need to get set up.</p>
<p>Inside of our index.html file, we're going to modify our script tag to include <code>type="module"</code>. This will allow us to start using ES modules in our code. Modify your script tag to be:</p>
<pre><code class="lang-javascript">&lt;script type=<span class="hljs-string">"module"</span> src=<span class="hljs-string">"script.js"</span>&gt;&lt;/script&gt;
</code></pre>
<p>Let’s start out by writing a simple add function. This function will take two numbers, add them together, and then return the result of that addition. We'll also call this function. We'll write this function in our <code>script.js</code> file:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
 <span class="hljs-keyword">return</span> a + b;
};
<span class="hljs-built_in">console</span>.log(add(<span class="hljs-number">5</span>, <span class="hljs-number">5</span>)); <span class="hljs-comment">//outputs 10</span>
</code></pre>
<p>So far, our <code>script.js</code> file is small with little code in it. But imagine that this application gets bigger and we have dozens of functions like this. This <code>script.js</code> file could get too big and become harder to maintain.  </p>
<p>Let’s avoid this problem by creating a module. We can do this by clicking 'Add File', within our replit. Remember, a module is just a file of related code. </p>
<p>We'll call our module <code>math.js</code>. We're going to remove this add function from our <code>script.js</code> file, and we're going to create a new file, <code>math.js</code>. This file will be our module where we'll keep our math-related functions. Let's place our add function inside this file:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// math.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
 <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>We've decided to call this module <code>math.js</code>, because we will create more math related functions in this file later on. </p>
<p>If we were to open this application and see it at a glance, we'd know that our math-related logic is inside this file. We don’t need to waste time coming into this application and searching for our math functions and wondering about where they are – we've organized them neatly into a file.</p>
<p>Next, let’s use the add function inside of our <code>script.js</code> file, even though the function itself now lives inside of the <code>math.js</code> file. To do this, we need to learn about ES module syntax. Let's go over the <code>export</code> and the <code>import</code> keywords. </p>
<h2 id="heading-the-export-keyword">The export keyword</h2>
<p>When you want to make a module available in other files besides the one it lives in, you can use the <code>export</code> keyword. Let’s use the <code>export</code> keyword with our add function so we can use it inside of our <code>script.js</code> file. </p>
<p>Let's add <code>export default</code> underneath our add function inside of math.js:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// math.js</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">add</span>(<span class="hljs-params">a, b</span>) </span>{
 <span class="hljs-keyword">return</span> a + b;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> add;
</code></pre>
<p>With the last line, we are making this add function available to use in other places besides the <code>math.js</code> module.</p>
<p>Another way of using the <code>export</code> keyword is to add it just before we define our function: </p>
<pre><code class="lang-js"><span class="hljs-comment">// math.js</span>

<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">add</span>(<span class="hljs-params">a, b</span>) </span>{
 <span class="hljs-keyword">return</span> a + b;
};
</code></pre>
<p>These are two different ways of using the <code>export</code> keyword, but both work the same.  </p>
<p>You might be wondering what that <code>default</code> keyword is that comes after <code>export</code>. We'll get to that in a minute. For now, let's actually use our <code>add</code> function in another file, now that we've exported it. </p>
<h2 id="heading-the-import-keyword">The import keyword</h2>
<p>We can use the import keyword to import our add function into our <code>script.js</code> file. Importing this function just means we'll gain access to that function and be able to use it within the file. Once the function is imported, we can use it:</p>
<pre><code class="lang-js"><span class="hljs-comment">// script.js</span>
<span class="hljs-keyword">import</span> add <span class="hljs-keyword">from</span> <span class="hljs-string">'./math.js'</span>;

<span class="hljs-built_in">console</span>.log(add(<span class="hljs-number">2</span>, <span class="hljs-number">5</span>)); <span class="hljs-comment">//outputs 7</span>
</code></pre>
<p>Here, with <code>./math.js</code>, we're using a relative import. To learn more about relative paths and absolute paths, check out this helpful <a target="_blank" href="https://stackoverflow.com/questions/21306512/difference-between-relative-path-and-absolute-path-in-javascript">StackOverflow</a> answer.</p>
<p>When we run this code, we can see the result of calling our add function, <code>7</code>. Now you can use the add function as many times as you’d like within this file. </p>
<p>The code for the add function itself is now out of sight, and we can use the add function without necessarily needing to look at the code for the function itself. </p>
<p>If we commented out the line <code>import add from './math.js'</code> for a moment, we'd suddenly get an error: <code>ReferenceError: add is not defined</code>. This is because <code>script.js</code> does not have access to the add function unless we explicitly import that function into this file. </p>
<p>We've exported our add function, imported it into our <code>script.js</code> file, and then called that function. </p>
<p>Let’s look into our <code>math.js</code> file again. As mentioned earlier, you may have been confused when you saw the word <code>default</code> with the <code>export</code> keyword. Let's talk more about the <code>default</code> keyword. </p>
<h2 id="heading-named-exports-versus-default-exports-in-javascript">Named exports versus default exports in JavaScript</h2>
<p>With ES modules, you can use named exports or default exports.</p>
<p>In our first example, we used a <strong>default export.</strong> With a default export, we exported only a single value (our add function) from our <code>math.js</code> module. </p>
<p>When using a default export, you can rename your import if you'd like to. In our <code>script.js</code> file, we can import our add function and call it addition (or any other name) instead:</p>
<pre><code class="lang-js"><span class="hljs-comment">// script.js</span>
<span class="hljs-keyword">import</span> addition <span class="hljs-keyword">from</span> <span class="hljs-string">'./math.js'</span>;

<span class="hljs-built_in">console</span>.log(addition(<span class="hljs-number">2</span>, <span class="hljs-number">5</span>)); <span class="hljs-comment">//outputs 7</span>
</code></pre>
<p>On the other hand, <strong>named exports</strong> are used to export <em>multiple values</em> from a module. </p>
<p>Let's create an example using named exports. Back in our <code>math.js</code> file, create two more functions, subtract and multiply, and place them underneath our add function. With a named export, you can just remove the <code>default</code> keyword:</p>
<pre><code class="lang-js"><span class="hljs-comment">// math.js</span>

<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">add</span>(<span class="hljs-params">a, b</span>) </span>{
 <span class="hljs-keyword">return</span> a + b;
};

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">subtract</span>(<span class="hljs-params">a, b</span>) </span>{
 <span class="hljs-keyword">return</span> a - b;
};

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">a, b</span>) </span>{
 <span class="hljs-keyword">return</span> a * b;
};
</code></pre>
<p>In <code>script.js</code>, let's remove all the previous code and import our subtract and multiply functions. To import the named exports, surround them in curly brackets:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { multiply, subtract } <span class="hljs-keyword">from</span> <span class="hljs-string">'./math.js'</span>;
</code></pre>
<p>Now we can use both of these functions inside of our <code>script.js</code> file:</p>
<pre><code class="lang-js"><span class="hljs-comment">// script.js</span>
<span class="hljs-keyword">import</span> { multiply, subtract } <span class="hljs-keyword">from</span> <span class="hljs-string">'./math.js'</span>;

<span class="hljs-built_in">console</span>.log(multiply(<span class="hljs-number">5</span>, <span class="hljs-number">5</span>));

<span class="hljs-built_in">console</span>.log(subtract(<span class="hljs-number">10</span>, <span class="hljs-number">4</span>))
</code></pre>
<p>If you'd like to rename a named export, you can do so with the <code>as</code> keyword:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> add, { subtract <span class="hljs-keyword">as</span> substractNumbers } <span class="hljs-keyword">from</span> <span class="hljs-string">'./math.js'</span>;

<span class="hljs-built_in">console</span>.log(substractNumbers(<span class="hljs-number">2</span>, <span class="hljs-number">5</span>));
</code></pre>
<p>Above, we've renamed our <code>subtract</code> import to <code>subtractNumbers</code>.</p>
<p>Let's get back to our add function. What if we'd like to use it again in our <code>script.js</code> file, alongside our <code>multiply</code> and <code>subtract</code> functions? We can do so like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> add, { multiply, subtract } <span class="hljs-keyword">from</span> <span class="hljs-string">'./math.js'</span>;

<span class="hljs-built_in">console</span>.log(multiply(<span class="hljs-number">5</span>, <span class="hljs-number">5</span>));

<span class="hljs-built_in">console</span>.log(subtract(<span class="hljs-number">10</span>, <span class="hljs-number">4</span>))

<span class="hljs-built_in">console</span>.log(add(<span class="hljs-number">10</span>, <span class="hljs-number">10</span>));
</code></pre>
<p>Now we've learned how to use ES modules. We've learned how to use the <code>export</code> keyword, the <code>import</code> keyword, and we've learned about the differences between named exports and default exports. And we've learned how to rename both our default exports and our named exports.  </p>
<h1 id="other">Other module systems in JavaScript</h1>

<p>When learning about modules, you may have seen or even used a different type of import, possibly one that looks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> models = <span class="hljs-built_in">require</span>(<span class="hljs-string">'./models'</span>)
</code></pre>
<p>This is where learning about modules in JavaScript can get confusing. Let's dive into a brief history of JavaScript modules to clear up the confusion.</p>
<p>The code example above using the <code>require</code> statement is CommonJS. CommonJS is another module system that can be used in JavaScript.   </p>
<p>When JavaScript was first created, it didn’t have a module system. Because JavaScript had no module system, developers created their own module systems on top of the language. </p>
<p>Different module systems were created and used over the years, including CommonJS. When working in a codebase at a company or in an open source project, you might spot different module systems being used. </p>
<p>Ultimately, ES modules were introduced as the standardized module system in JavaScript. </p>
<p>In this article, we've learned about what modules are and why developers use them. We've learned about how ES modules work and the different kinds of module systems in JavaScript.</p>
<p>If you enjoyed this post, join my <a target="_blank" href="https://madisonkanna.us14.list-manage.com/subscribe/post?u=323fd92759e9e0b8d4083d008&amp;id=033dfeb98f">coding club</a>, where we tackle coding challenges together every Sunday and support each other as we learn new technologies.</p>
<p>If you have feedback or questions on this post, or find me on Twitter <a target="_blank" href="https://twitter.com/Madisonkanna">@madisonkanna</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Modules – Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ A module is a function or group of similar functions. They are grouped together within a file and contain the code to execute a specific task when called into a larger application. You create modules to better organize and structure your codebase. Yo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-modules-explained-with-examples/</link>
                <guid isPermaLink="false">66d4618ed14641365a05098f</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kingsley Ubah ]]>
                </dc:creator>
                <pubDate>Wed, 28 Jul 2021 16:27:49 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/07/what-is-a-module.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A module is a function or group of similar functions. They are grouped together within a file and contain the code to execute a specific task when called into a larger application.</p>
<p>You create modules to better organize and structure your codebase. You can use them to break down large programs into smaller, more manageable, and more independent chunks of code which carry out a single or a couple of related tasks.</p>
<p>Modules should be:</p>
<ol>
<li><p><strong>Independent/Self-contained:</strong> A module has to be as detached from other dependencies as possible.</p>
</li>
<li><p><strong>Specific:</strong> A module needs to be able to perform a single or a related group of tasks. The core essence of creating them in the first place is to create separate functionalities. One module, one (kind of) task.</p>
</li>
<li><p><strong>Reusable:</strong> A module has to be easy to integrate into various kinds of programs to perform its task.</p>
</li>
</ol>
<p>To better explain, let me give you an analogy:</p>
<p>Suppose we want to build a huge house from the ground up. All the tools we need to set up the building are all pilled up within just one room.</p>
<p>In such a situation, organizing the tools in the right way so we can start building would be difficult.</p>
<p>Instead of having the separate dependencies pilled up in just one room, we should instead organize each set of related tools and group them into different rooms. Each room is independent and self-contained with its tools solving specific tasks.</p>
<p>We could put up labels like: <strong>"these tools are for roofing",</strong> "<strong>these tools are for brick laying</strong>", "<strong>these tools are for foundation digging</strong>" and so on.</p>
<p>Whenever we want a tool to carry out a particular task, we know in which room exactly to find it. That way, everything is much more organized and locatable.</p>
<p>Also, say we are done building the house and then decide to build something different. We will still have at our disposal the same set of tools. This enforces the principle of <strong>reusability</strong>. Modules are reusable because they are self-contained.</p>
<h2 id="heading-example-of-a-module">Example of a Module</h2>
<p>Now in the context of code, modules are very important.</p>
<p>Let's consider a simplified illustration of this with an e-commerce application which allows people and businesses to sell products online. This program will typically be composed of two or more unrelated tasks. For example,</p>
<ul>
<li><p>a program for creating an account,</p>
</li>
<li><p>a program to validate the information,</p>
</li>
<li><p>another program to process payments</p>
</li>
<li><p>another program to calculate the user ratings</p>
</li>
</ul>
<p>and so on.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/main-task.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Instead of having all of those unrelated programs together in one module/file, it is a better practice to create several files, or modules, for each of those tasks. In such a case, the modules become dependencies.</p>
<p>Then from the main app or program, you simply import/load the dependencies (i.e the modules you need) and execute them accordingly. As a result, your main app becomes cleaner and more minimal.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/07/modules.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>main.js has been broken down into four modules</em></p>
<p>Assuming you need to process payments in some other application in the codebase, for example, it becomes very easy to reuse the same functionality. No need to copy and paste or code a new function from scratch.</p>
<h2 id="heading-javascript-modules">JavaScript Modules</h2>
<p>A module in JavaScript is just a file containing related code.</p>
<p>In JavaScript, we use the <code>import</code> and <code>export</code> keywords to share and receive functionalities respectively across different modules.</p>
<ul>
<li><p>The <code>export</code> keyword is used to make a variable, function, class or object accessible to other modules. In other words, it becomes a public code.</p>
</li>
<li><p>The <code>import</code> keyword is used to bring in public code from another module.</p>
</li>
</ul>
<p>Let's look at a simple example of this:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPower</span>(<span class="hljs-params">decimalPlaces</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-number">10</span> ** decimalPlaces;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">capitalize</span>(<span class="hljs-params">word</span>) </span>{
    <span class="hljs-keyword">return</span> word[<span class="hljs-number">0</span>].toUpperCase() + word.slice(<span class="hljs-number">1</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">roundToDecimalPlace</span>(<span class="hljs-params">number, decimalPlaces = <span class="hljs-number">2</span></span>) </span>{
    <span class="hljs-keyword">const</span> round = getPower(decimalPlaces);
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.round(number * round) / round;
}

<span class="hljs-keyword">export</span> { capitalize, roundToDecimalPlace };
</code></pre>
<p>This module has three functions defined in it:</p>
<ul>
<li><p><code>getPower</code>: This function gets the power of a number</p>
</li>
<li><p><code>capitalize</code>: This function capitalizes the first letter in a word</p>
</li>
<li><p><code>roundToDecimalPlace</code>: This function rounds a given number to a specified number of decimal places.</p>
</li>
</ul>
<p>At the end of the file, you can see that two of the three functions were exported. In other words, they became public functions which could be used by any other script.</p>
<p>To export two functions out of the three, you use the <code>export</code> keyword, followed by an object containing the functions you want to make accessible. Once you do this, the functions can be accessed by any program within that codebase which require them.</p>
<p>Let's take a look at how we can use them:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { capitalize, roundToDecimalPlace } <span class="hljs-keyword">from</span> <span class="hljs-string">'./main'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayTotal</span>(<span class="hljs-params">name, total</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`<span class="hljs-subst">${capitalize(name)}</span>, your total cost is: <span class="hljs-subst">${roundToDecimalPlace(total)}</span>`</span>;
}

displayTotal(<span class="hljs-string">'kingsley'</span>, <span class="hljs-number">20.4444444</span>);
<span class="hljs-comment">// "Kingsley, your total cost is: 20.44"</span>

<span class="hljs-keyword">export</span> { displayTotal };
</code></pre>
<p>The <code>displayTotal.js</code> module does not have <code>capitalize()</code> and <code>roundToDecimalPlace()</code> but wants to use the capitalize and round-to-decimal-place functionality. So how did we bring it in? With <code>import</code>!</p>
<p>We did this by using the <code>import</code> keyword followed by the name of the functions we want to import from the module, which in our case are <code>capitalize</code> and <code>roundToDecimalPlace</code>.</p>
<p>What if you only wanted to import the <code>capitalize</code> function into your program?</p>
<p>Simple – import only <code>capitalize()</code>, like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { capitalize } <span class="hljs-keyword">from</span> <span class="hljs-string">'./main'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">warn</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`I am warning you, <span class="hljs-subst">${capitalize(name)}</span>!`</span>;
}

warn(<span class="hljs-string">'kingsley'</span>);
<span class="hljs-comment">// I am warning you, Kingsley!</span>

<span class="hljs-keyword">export</span> { warn };
</code></pre>
<blockquote>
<p>N/B: Understanding how file structuring works is very important when working with modules. In the above example, we are simply importing from a file which exists in the same directory, which is why we use the notation <code>'./import'</code>.</p>
</blockquote>
<p>If you want to import every public function from another module, use the asterisk <code>*</code> keyword:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> mainfunctions <span class="hljs-keyword">from</span> <span class="hljs-string">'./main'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">warn</span>(<span class="hljs-params">name</span>) </span>{
<span class="hljs-keyword">return</span> <span class="hljs-string">`I am warning you, <span class="hljs-subst">${mainfunctions.capitalize(name)}</span>!`</span>;
}
warn(<span class="hljs-string">'kingsley'</span>);
<span class="hljs-comment">// I am warning you, Kingsley!</span>

<span class="hljs-keyword">export</span> { warn };
</code></pre>
<blockquote>
<p><strong>TIP</strong>: If you're importing everything from a module, you should use the asterisk instead of explicitly spelling out all the functions one-by-one.</p>
</blockquote>
<p>You may have noticed the <code>as</code> keyword. We use this to import the public functions into a new object, which in our case is the <code>mainfunctions</code> object. We then access and call the functions we want to use in our program.</p>
<p>So far, we have only considered examples where the export happens at the end of the file. But you can equally export a function, variable, or class by registering the <code>export</code> keyword just in front of its definition, like so:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPower</span>(<span class="hljs-params">decimalPlaces</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-number">10</span> ** decimalPlaces;
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">capitalize</span>(<span class="hljs-params">word</span>) </span>{
    <span class="hljs-keyword">return</span> word[<span class="hljs-number">0</span>].toUpperCase() + word.slice(<span class="hljs-number">1</span>);
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">roundToDecimalPlace</span>(<span class="hljs-params">number, decimalPlaces = <span class="hljs-number">2</span></span>) </span>{
    <span class="hljs-keyword">const</span> round = getPower(decimalPlaces);
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.round(number * round) / round;
}
</code></pre>
<p>If you compare this with the first example, you will notice this syntactic difference:</p>
<ul>
<li>In the first example, the <code>export</code> keyword was used to export two functions at the end of the script. In the above example, the <code>export</code> keyword is attached to both functions when they are being defined.</li>
</ul>
<p>However, they both deliver the same outcome: <code>capitalize</code> and <code>roundToDecimalPlace</code> will both get exported.</p>
<h2 id="heading-default-exports">Default Exports</h2>
<p>If you want to export all three functions but intend to make one of them a default (perhaps because you are most likely to use that single function), you simply use the <code>default</code> keyword.</p>
<p>The default keyword makes importing a function easier. Let's consider the following example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPower</span>(<span class="hljs-params">decimalPlaces</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-number">10</span> ** decimalPlaces;
    }

<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">capitalize</span>(<span class="hljs-params">word</span>) </span>{
    <span class="hljs-keyword">return</span> word[<span class="hljs-number">0</span>].toUpperCase() + word.slice(<span class="hljs-number">1</span>);
    }

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">roundToDecimalPlace</span>(<span class="hljs-params">number, decimalPlaces = <span class="hljs-number">2</span></span>) </span>{
    <span class="hljs-keyword">const</span> round = getPower(decimalPlaces);
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.round(number * round) / round;
    }
</code></pre>
<p>As you can see, we have made <code>capitalize</code> our default function. This essentially means we have given it some sort of privilege.</p>
<p>Say we want to import the <code>capitalize</code> function from the module into another program. The syntax for that will be very similar, except you don't have to import the function into curly braces:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> capitalize <span class="hljs-keyword">from</span> <span class="hljs-string">'./main'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">warn</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`I am warning you, <span class="hljs-subst">${capitalize(name)}</span>!`</span>;
}

warn(<span class="hljs-string">'kingsley'</span>);
<span class="hljs-comment">// I am warning you, Kingsley!</span>

<span class="hljs-keyword">export</span> { warn };
</code></pre>
<p>If you want to import the default function along with any other functions, you mix the bare 'default' function with other functions in curly braces:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> capitalize, { getPower } <span class="hljs-keyword">from</span> <span class="hljs-string">'./main'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">warn</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`I am warning you, <span class="hljs-subst">${capitalize(name)}</span>!`</span>;
}

warn(<span class="hljs-string">'kingsley'</span>);
<span class="hljs-comment">// I am warning you, Kingsley!</span>

<span class="hljs-keyword">export</span> { warn };
</code></pre>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Modules are independent and self-contained chunks of code. You create them by splitting up a larger program into logical parts or dependencies.</p>
<p>Modules should be independent, specialized, and reusable.</p>
<p>You use the <code>import</code> and <code>export</code> keywords to interchange functionalities between modules in JavaScript.</p>
<p>You use the <code>default</code> keyword to specify a function, object, variable, or class that you want to be a first-choice import.</p>
<p>With this, we have covered the basics of modules in JavaScript.</p>
<p>I hope you got something valuable from this article. I write programming-related articles every week on my <a target="_blank" href="https://ubahthebuilder.tech">personal blog</a></p>
<p>Thank you for reading.</p>
<blockquote>
<p><strong>P/S</strong>: If you are learning JavaScript, I created an eBook which teaches 50 topics in JavaScript with hand-drawn digital notes. <a target="_blank" href="https://ubahthebuilder.gumroad.com/l/js-50">Check it out here</a>.</p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Python's datetime Module – How to Handle Dates in Python ]]>
                </title>
                <description>
                    <![CDATA[ By Suchandra Datta In this quick guide to Python's datetime module, you'll learn how to parse dates, extract meaningful information from dates, handle timedelta objects and much more.  So without further ado let's start counting time with Python! Mos... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/python-datetime-module/</link>
                <guid isPermaLink="false">66d85267b6622019db605220</guid>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 01 Mar 2021 15:59:54 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/6022ad400a2838549dcc1f89.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Suchandra Datta</p>
<p>In this quick guide to Python's <code>datetime</code> module, you'll learn how to parse dates, extract meaningful information from dates, handle <code>timedelta</code> objects and much more. </p>
<p>So without further ado let's start counting time with Python!</p>
<p>Most programming languages provide libraries for easy handling of dates. Python offers the powerful <code>datetime</code> module with its many functions and lucid documentation which makes parsing dates easy. </p>
<p>This article lists out some of the most important functions from this module, how it can be applied for real-world situations, and some tricky things to watch out for when using it. </p>
<h2 id="heading-how-to-convert-timestamps-to-datetime-objects-using-strptime">How to Convert Timestamps to <code>datetime</code> Objects Using <code>strptime()</code></h2>
<p>Dates can give us a lot of information like the month, year, day, weekday and whether it's a holiday or not. <code>strptime()</code> converts a timestamp in the form of a string to a <code>datetime</code> object which gives us a lot of extra functionalities. This function expects a string and the format of the timestamp. </p>
<pre><code><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime

d = datetime.strptime(<span class="hljs-string">"21-02-2021 18:46:00"</span>, <span class="hljs-string">"%d-%m-%Y %H:%M:%S"</span>)
</code></pre><p>The string 21-02-2021 18:46:00 is converted to a suitable <code>datetime</code> using the format specified. Some of the most useful directives are:</p>
<ul>
<li><code>%d</code> for day of month as a zero-padded decimal like 01, 02, 03 </li>
<li><code>%m</code> for month as a zero-padded decimal number</li>
<li><code>%Y</code> for year with century as a decimal number</li>
<li><code>%H</code> for 24 hour clock with a zero-padded hour value</li>
<li><code>%M</code> for zero-padded minutes, and </li>
<li><code>%S</code> for zero-padded seconds.</li>
</ul>
<p>This collection of format specifiers is enough to get you started. For more options, you can browse through the docs linked <a target="_blank" href="https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior">here</a>. </p>
<h3 id="heading-how-to-get-the-current-timestamp-value">How to Get the Current Timestamp Value</h3>
<p>Suppose you want to store data to a database with the current timestamp as a key. To obtain the current timestamp, you just need 1 line of code:</p>
<pre><code class="lang-python"><span class="hljs-comment">#Obtain the current timestamp</span>

<span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime
print(datetime.now())
</code></pre>
<h3 id="heading-how-to-know-what-day-it-is">How to Know What Day it Is</h3>
<p>Let's say we need to know the day of the week. We can use the <code>weekday()</code> function which returns a numeric code for the day of the week, zero through six, where zero represents Monday, one represents Tuesday, and so on. </p>
<p>The output could be used with a switch statement to convert the numeric code to the required day name or you could use a list like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-169.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-generate-a-list-of-dates-from-a-given-date">How to Generate a List of Dates from a Given Date</h3>
<p>Let's say we know how many pizzas people ordered up until today and we are interested in predicting pizza sales for the next week. </p>
<p>So, given today's date we need all dates for next week for our required analysis. But we don't want to worry about leap years, century years, and so on. Here's one way to do it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-137.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-work-with-timedelta-objects">How to Work with <code>timedelta</code> Objects</h3>
<p>As the name suggests, <code>timedelta</code> objects represent a time duration between two dates. Let's say that we have two dates and we need to know how much time has passed between them.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-138.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><code>timedelta</code> objects require several arguments like days, seconds, microseconds, milliseconds, minutes, hours and weeks. Default values for all are zero. Let's find out the difference in hours between 2 dates.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-139.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>What went wrong? <code>timedelta</code> does not store anything internally except for days, seconds, and microseconds, so we need to convert them as shown below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-141.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-get-string-representation-of-dates-from-datetime-or-date-objects-using-strftime">How to Get String Representation of Dates from <code>datetime</code> or Date Objects using <code>strftime</code></h3>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/image-170.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If we print the <code>datetime</code> object itself, the date is printed in ISO format. Using <code>strftime</code>, we pass a format string to control the string representation of the date.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>If you've read this far, congrats – you've learned how to parse dates according to a specified format, obtain the current timestamp value, get the weekday, get a list of dates, use timedelta objects, and get the date as a string back from objects. Whew!</p>
<p>This is a compiled collection based on my own numerous internet searches and endless perusal of the official docs. </p>
<p>Thank you for taking some time out of your busy schedule to read this. Hope you enjoyed reading it just as much as I loved writing it. Have fun parsing dates in Python!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Node Module Exports Explained – With JavaScript Export Function Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Stanley Nguyen One of the most powerful things about software development is the ability to reuse and build upon the foundations of other people. This code sharing has helped software progress at an amazing rate. Such a wonderful mechanism is crit... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/node-module-exports-explained-with-javascript-export-function-examples/</link>
                <guid isPermaLink="false">66d4614d246e57ac83a2c7d9</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 17 Feb 2021 20:16:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/02/cover-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Stanley Nguyen</p>
<p>One of the most powerful things about software development is the ability to reuse and build upon the foundations of other people. This code sharing has helped software progress at an amazing rate.</p>
<p>Such a wonderful mechanism is critical on a micro-level for both individual projects and teams. </p>
<p>For Node.js, this process of code sharing – both within individual projects and in external npm dependencies – is facilitated using <code>module.exports</code> or <code>exports</code>.</p>
<h1 id="heading-how-node-modules-work">How Node Modules Work</h1>
<p>How do we use module exports to plug an external module, or sensibly break our project down into multiple files (modules)?</p>
<p>The Node.js module system was created because its designers didn't want it to suffer from the same problem of broken global scope, like its browser counterpart. They implemented <a target="_blank" href="https://en.wikipedia.org/wiki/CommonJS">CommonJS specification</a> to achieve this.</p>
<p>The two important pieces of the puzzle are <code>module.exports</code> and the <code>require</code> function.</p>
<h2 id="heading-how-moduleexports-works">How module.exports works</h2>
<p><code>module.exports</code> is actually a property of the <code>module</code> object. This is how the <code>module</code> object looks like when we <code>console.log(module)</code>:</p>
<pre><code class="lang-bash">Module {
  id: <span class="hljs-string">'.'</span>,
  path: <span class="hljs-string">'/Users/stanleynguyen/Documents/Projects/blog.stanleynguyen.me'</span>,
  exports: {},
  parent: null,
  filename: <span class="hljs-string">'/Users/stanleynguyen/Documents/Projects/blog.stanleynguyen.me/index.js'</span>,
  loaded: <span class="hljs-literal">false</span>,
  children: [],
  paths: [
    <span class="hljs-string">'/Users/stanleynguyen/Documents/Projects/blog.stanleynguyen.me/node_modules'</span>,
    <span class="hljs-string">'/Users/stanleynguyen/Documents/Projects/node_modules'</span>,
    <span class="hljs-string">'/Users/stanleynguyen/Documents/node_modules'</span>,
    <span class="hljs-string">'/Users/stanleynguyen/node_modules'</span>,
    <span class="hljs-string">'/Users/node_modules'</span>,
    <span class="hljs-string">'/node_modules'</span>
  ]
}
</code></pre>
<p>The above object basically describes an encapsulated module from a JS file with <code>module.exports</code> being the exported component of any types - object, function, string, and so on. Default exporting in a Node.js module is as simple as this:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">anExportedFunc</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">"yup simple as that"</span>;
};
</code></pre>
<p>There's another way of exporting from a Node.js module called "named export". Instead of assigning the whole <code>module.exports</code> to a value, we would assign individual properties of the default <code>module.exports</code> object to values. Something like this:</p>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports.anExportedFunc = <span class="hljs-function">() =&gt;</span> {};
<span class="hljs-built_in">module</span>.exports.anExportedString = <span class="hljs-string">"this string is exported"</span>;

<span class="hljs-comment">// or bundled together in an object</span>
<span class="hljs-built_in">module</span>.exports = {
  anExportedFunc,
  anExportedString,
};
</code></pre>
<p>Named export can also be done more concisely with the module-scoped <code>exports</code> predefined variable, like this:</p>
<pre><code class="lang-js"><span class="hljs-built_in">exports</span>.anExportedFunc = <span class="hljs-function">() =&gt;</span> {};
<span class="hljs-built_in">exports</span>.anExportedString = <span class="hljs-string">"this string is exported"</span>;
</code></pre>
<p>However, assigning the whole <code>exports</code> variable to a new value won't work (we will discuss why in a later section), and often confuses Node.js developers.</p>
<pre><code class="lang-js"><span class="hljs-comment">// This wont work as we would expect</span>
<span class="hljs-built_in">exports</span> = {
  anExportedFunc,
  anExportedString,
};
</code></pre>
<p>Imagine that Node.js module exports are shipping containers, with <code>module.exports</code> and <code>exports</code> as port personnel whom we would tell which "ship" (that is, values) that we want to get to a "foreign port" (another module in the project). </p>
<p>Well, "default export" would be telling <code>module.exports</code> which "ship" to set sail while "named export" would be loading different containers onto the ship that <code>module.exports</code> is going to set sail.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/02/ship-analogy.png" alt="Image" width="600" height="400" loading="lazy">
<em>My "flagship" analogy for Node.js module.exports' role</em></p>
<p>Now that we have sent the ships sailing, how do our "foreign ports" reel in the exported ship?</p>
<h2 id="heading-how-the-nodejs-require-keyword-works">How the Node.js require keyword works</h2>
<p>On the receiving end, Node.js modules can import by <code>require</code>-ing the exported value.</p>
<p>Let's say this was written in <code>ship.js</code>:</p>
<pre><code class="lang-js">...
module.exports = {
  containerA,
  containerB,
};
</code></pre>
<p>We can easily import the "ship" in our <code>receiving-port.js</code>:</p>
<pre><code class="lang-js"><span class="hljs-comment">// importing the whole ship as a single variable</span>
<span class="hljs-keyword">const</span> ship = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./ship.js"</span>);
<span class="hljs-built_in">console</span>.log(ship.containerA);
<span class="hljs-built_in">console</span>.log(ship.containerB);
<span class="hljs-comment">// or directly importing containers through object destructuring</span>
<span class="hljs-keyword">const</span> { containerA, containerB } = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./ship.js"</span>);
<span class="hljs-built_in">console</span>.log(containerA);
<span class="hljs-built_in">console</span>.log(containerB);
</code></pre>
<p>An important point to note about this foreign port operator – <code>require</code> – is that the person is adamant about receiving ships that were <strong>sent by <code>module.exports</code> from the other side of the sea</strong>. This leads us to the next section where we will address a common point of confusion.</p>
<h2 id="heading-moduleexports-vs-exports-what-is-the-difference-and-which-do-you-use-when"><code>module.exports</code> vs <code>exports</code> – What is the difference and which do you use when?</h2>
<p>Now that we have gone through the basics of module exporting and requiring, it's time to address one of the common sources of confusion in Node.js modules.</p>
<p>This is a common module exports mistake that people who are starting out with Node.js often make. They assign <code>exports</code> to a new value, thinking that it's the same as "default exporting" through <code>module.exports</code>. </p>
<p>However, this will not work because:</p>
<ul>
<li><code>require</code> will only use the value from <code>module.exports</code></li>
<li><code>exports</code> is a module-scoped variable that refers to <code>module.exports</code> initially</li>
</ul>
<p>So by assigning <code>exports</code> to a new value, we're effectively pointing the value of <code>exports</code> to another reference away from the initial reference to the same object as <code>module.exports</code>. </p>
<p>If you want to learn more about this technical explanation, <a target="_blank" href="https://nodejs.org/api/modules.html#modules_exports_shortcut">the Node.js official documentation</a> is a good place to start.</p>
<p>Back to the analogy that we made previously using ships and operators: <code>exports</code> is another port personnel that we could inform about the outgoing ship. At the start, both <code>module.exports</code> and <code>exports</code> have the same piece of information about the outgoing "ship". </p>
<p>But what if we tell <code>exports</code> that the outgoing ship will be a different one (that is, assigning <code>exports</code> to a completely new value)? Then, whatever we tell them afterwards (like assigning properties of <code>exports</code> to values) won't be on the ship that <code>module.exports</code> is actually setting sail to be received by <code>require</code>.</p>
<p>On the other hand, if we only tell <code>exports</code> to "load some containers on the outgoing ship" (assigning properties of <code>exports</code> to value), we would actually end up loading "containers" (that is, property value) onto the ship that is actually being set sail.</p>
<p>Based on the common mistake explained above, we could definitely develop some good conventions around using CommonJS modules in Node.js.</p>
<h2 id="heading-nodejs-export-best-practices-a-sensible-strategy">Node.js export best practices – a sensible strategy</h2>
<p>Of course the convention offered below is entirely from my own assessments and reasonings. If you have a stronger case for an alternative, please don't hesitate to tweet me <a target="_blank" href="https://twitter.com/stanley_ngn">@stanley_ngn</a>.</p>
<p>The main things I want to achieve with this convention are:</p>
<ul>
<li>eliminating confusion around <code>exports</code> vs <code>module.exports</code></li>
<li>ease of reading and higher glanceability with regards to module exporting</li>
</ul>
<p>So I'm proposing that we consolidate exported values at the bottom of the file like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// default export</span>
<span class="hljs-built_in">module</span>.exports = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">defaultExportedFunction</span>(<span class="hljs-params"></span>) </span>{};
<span class="hljs-comment">// named export</span>
<span class="hljs-built_in">module</span>.exports = {
  something,
  anotherThing,
};
</code></pre>
<p>Doing so would eliminate any disadvantages in terms of conciseness that <code>module.exports</code> have versus shorthand <code>exports</code>. This would remove all incentives for us to use the confusing and potentially harmful <code>exports</code>. </p>
<p>This practice would also make it very easy for code readers to glance at and learn about exported values from a specific module.</p>
<h2 id="heading-going-beyond-commonjs">Going beyond CommonJS</h2>
<p>There's a new, and better (of course!) standard that's recently been introduced to Node.js called <code>ECMAScript modules</code>. <a target="_blank" href="https://nodejs.org/api/esm.html">ECMAScript modules</a> used to only be available in code that would eventually need transpilation from <a target="_blank" href="https://babeljs.io/">Babel</a>, or as part of an experimental feature in Node.js version 12 or older. </p>
<p>It's a pretty simple and elegant way of handling module exporting. The gist of it can be summed up with the default export being:</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">exportedFunction</span>(<span class="hljs-params"></span>) </span>{}
</code></pre>
<p>and the named export looking like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// named exports on separate LOC</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> constantString = <span class="hljs-string">"CONSTANT_STRING"</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> constantNumber = <span class="hljs-number">5</span>;
<span class="hljs-comment">// consolidated named exports</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  constantString,
  constantNumber,
};
</code></pre>
<p>These values can then easily be imported on the receiving end, like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// default exported value</span>
<span class="hljs-keyword">import</span> exportedFunction <span class="hljs-keyword">from</span> <span class="hljs-string">"exporting-module.js"</span>;
<span class="hljs-comment">// import named exported values through object destructuring</span>
<span class="hljs-keyword">import</span> { constantString, constantNumber } <span class="hljs-keyword">from</span> <span class="hljs-string">"exporting-module.js"</span>;
</code></pre>
<p>This results in no more confusion from <code>module.exports</code> vs <code>exports</code> and a nice, human-sounding syntax! </p>
<p>There are definitely projects that are yet to be migrated to Node.js version 14 and above and so can't use this new syntax. </p>
<p>However, if you do have a chance (because you are starting a new project, or your project has successfully been migrated to Node.js 14 and above), there's no reason not to switch to this awesome futuristic way of doing things.</p>
<h3 id="heading-thank-you-for-reading">Thank you for reading!</h3>
<p>Last but not least, if you like my writings, please head over to <a target="_blank" href="https://blog.stanleynguyen.me/">my blog</a> for similar commentaries and follow <a target="_blank" href="https://twitter.com/stanley_ngn">me on Twitter</a>. 🎉</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Practical guide to ES6 modules ]]>
                </title>
                <description>
                    <![CDATA[ By Dler Ari One of the major challenges when building a web-app is how quickly you can scale and respond to the market needs. When the demand (requirements) increases, the capabilities (features) increase too. It is therefore important to have a soli... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-es6-modules-and-why-theyre-important-a9b20b480773/</link>
                <guid isPermaLink="false">66d45e4d052ad259f07e4aad</guid>
                
                    <category>
                        <![CDATA[ ES6 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 27 Nov 2018 00:02:21 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*PGxaa-3OODqO9Qxz0qnQzA.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dler Ari</p>
<p>One of the major challenges when building a web-app is how quickly you can scale and respond to the market needs. When the demand (requirements) increases, the capabilities (features) increase too. It is therefore important to have a solid architectural structure so that the app grows organically. We don’t want to end up in situations where the app can’t scale because everything in the app is deeply entangled.</p>
<blockquote>
<p>Write code that is easy to delete, not easy to extend.  </p>
<ul>
<li>Tef, Programming is Terrible</li>
</ul>
</blockquote>
<p>In this article, we’ll create a simple dashboard using ES6 modules, and then present optimization techniques for improving the folder structure and ease write less code. Let’s see dive into why ES6 modules are important, and how to effectively apply it.</p>
<blockquote>
<p>JavaScript has had modules for a long time. However, they were implemented via libraries, not built into the language. ES6 is the first time that JavaScript has built-in modules (<a target="_blank" href="http://exploringjs.com/es6/ch_modules.html">source</a>).</p>
</blockquote>
<p>TL;DR — If you want to see a practical example where we create a dashboard using ES6 modules from an architectural design layout, jump to section 4.</p>
<h3 id="heading-heres-what-well-address">Here’s what we’ll address</h3>
<ol>
<li>Why ES6 modules are needed</li>
<li>Back in the days when scripts were loaded manually</li>
<li>How ES6 modules work (<code>import</code> vs <code>export</code> )</li>
<li>Let’s build a dashboard with modules</li>
<li>Optimization techniques for dashboard example</li>
</ol>
<blockquote>
<p>If you want to become a better web developer, start your own business, teach others, or improve your development skills, I’ll be posting weekly tips and tricks on the latest web languages.</p>
</blockquote>
<h3 id="heading-1-why-es6-modules-are-needed">1. Why ES6 modules are needed</h3>
<p>Let’s view a couple of scenarios as to why modules are relevant.</p>
<h4 id="heading-scenario-1-dont-reinvent-the-wheel">Scenario 1 — Don’t reinvent the wheel</h4>
<p>As developers, we often recreate things that has already been created without even being aware, or copy and paste stuff to reduce time. In the end, it adds up, and we are left with x number of identical copies scattered throughout the app. And for each time we need to change something, we must do it x times depending on how many copies we have.</p>
<p><strong>Example</strong><br>For instance, imagine a car factory trying to reinvent the engine every time it produced a new car, or an architect starting from scratch after each drawing. It’s not impossible to do this, but then what is the point of knowledge if you cannot reuse the experience you’ve acquired.</p>
<h4 id="heading-scenario-2-knowledge-barrier">Scenario 2— Knowledge barrier</h4>
<p>If the system is deeply entangled, and lack of documentation, its difficult for old/new developers to learn how the app works, and how things are connected.</p>
<p><strong>Example</strong><br>For instance, a developer should be able to see what the outcome of a change is without guessing, otherwise we end up with lots of errors without knowing where to start. A solution is to use modules for encapsulating behaviour, we can easily narrow down the debug process and quickly identify the root of the problem.</p>
<blockquote>
<p>I’ve recently written an article about <a target="_blank" href="https://codeburst.io/developers-that-constantly-want-to-learn-new-things-heres-a-tip-7a16e42302e4">“Developers that constantly want to learn new things”</a>, with tips on how to improve knowledge.</p>
</blockquote>
<h4 id="heading-scenario-3-unexpected-behavior">Scenario 3— Unexpected behavior</h4>
<p>By avoiding separation-of-concerns (design principle), it can lead to unexpected behaviour.</p>
<p><strong>Example</strong><br>For instance, let’s say someone increases the volume in the car, and that starts the windshield wipers. That is an example of an unexpected behaviour, and not something we want in our application.</p>
<p>In short, we need ES6 modules in order to effectively reuse, maintain, separate and encapsulate internal behaviour from external behaviour. It’s not about making the system complex, but having the ability to easily scale and delete stuff without breaking the system.</p>
<h3 id="heading-2-back-in-the-days-when-scripts-were-loaded-manually">2. Back in the days when scripts were loaded manually</h3>
<p>If you’ve done web development for a couple of years, then you’ve definitely encountered dependency conflicts such as scripts not loading in the right order, or that the elements of the DOM tree cannot be accessed by JS.</p>
<p>The reason is that the HTML on a page is loaded in the order in which it appears, which means we cannot load scripts before the content inside the <code>&lt;bo</code>dy&gt; element has finished loading.</p>
<p>For instance, if you try to access an element within the <code>&lt;body&gt;</code> tag <code>using document.getElementById("id-name")</code> and the element is not loaded yet, then you get an undefined error. To make sure that scripts are loaded properly we can use and defer async. The former will make sure that each script loads in the order it appears, while the latter loads the script whenever it becomes available.</p>
<p>The old fashioned way of solving such issue was to load the scripts right before the <code>&lt;/body&gt;</code> element.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

  <span class="hljs-comment">&lt;!--HTML content goes here--&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/jquery.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/script2.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/script3.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/script4.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>But in the long run, the number of scripts adds up and we may end up with 10+ scripts while trying to maintain version and dependency conflicts.</p>
<h4 id="heading-separation-of-concerns">Separation-of-concerns</h4>
<p>In general, loading scripts as shown above is not a good idea in terms of performance, dependencies and maintainability. We don’t want the <code>index.html</code> file to have the responsibility of loading all the scripts — we need some sort of structure and separation of logic.</p>
<p>The solution is to utilize ES6’s syntax, <code>import</code> and <code>export</code> statements, an elegant and maintainable approach that allows us to keep things separated, and only available when we need it.</p>
<h4 id="heading-the-import-and-export-statements">The <code>import</code> and <code>export statements</code></h4>
<p>The <code>export</code> keyword is used when we want to make something available somewhere, and the <code>import</code> is used to access what <code>export</code> has made available.</p>
<blockquote>
<p>The thumb rule is, in order to <code>import</code> something, you first need to <code>export</code> it.</p>
</blockquote>
<p>And what can we actually <code>export</code>?</p>
<ul>
<li>A variable</li>
<li>An object literal</li>
<li>A class</li>
<li>A function</li>
<li>++</li>
</ul>
<p>To simplify the example as shown above, we can wrap all scripts one file.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { jquery } <span class="hljs-keyword">from</span> <span class="hljs-string">'./js/jquery.js'</span>;
<span class="hljs-keyword">import</span> { script2 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./js/script2.js'</span>;
<span class="hljs-keyword">import</span> { script3 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./js/script3.js'</span>;
<span class="hljs-keyword">import</span> { script4 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./js/script4.js'</span>;
</code></pre>
<p>And then just load <code>app.js</code> script in our <code>index.html</code>. But first, in order to make it work, we need to use <code>type="module"</code> (<a target="_blank" href="https://caniuse.com/#search=modules">source</a>) so that we can use the <code>import</code> and <code>export</code> for working with modules.</p>
<pre><code class="lang-js">&lt;!DOCTYPE html&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span></span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

  <span class="hljs-comment">&lt;!--HTML content goes here--&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"module"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"js/app.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span></span>
&lt;/html&gt;
</code></pre>
<p>As you can see, the <code>index.html</code> is now responsible for one script, which makes it easier to maintain and scale. In short, the <code>app.js</code> script becomes our entry point that we can use to bootstrap our application.</p>
<p>Note: I would not recommend having all scripts loaded in one file such as <code>app.js</code>, except the ones that require it.</p>
<p>Now that we have seen how we can use the <code>import</code> and <code>export</code> statements, let’s see how it works when working with modules in practice.</p>
<h3 id="heading-3-how-es6-modules-work">3. How ES6 modules work</h3>
<p>What is the difference between a module and a component? A module is a collection of small independent units (components) that we can reuse in our application.</p>
<h4 id="heading-whats-the-purpose"><strong>What’s the purpose?</strong></h4>
<ul>
<li>Encapsulate behaviour</li>
<li>Easy to work with</li>
<li>Easy to maintain</li>
<li>Easy to scale</li>
</ul>
<p>Yes, it makes development easier!</p>
<h4 id="heading-so-what-is-a-component-really">So what is a component really?</h4>
<p>A component may be a variable, function, class and so forth. In other words, everything that can be exported by the <code>_export_</code> statement is a component (or you can call it a block, a unit etc).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*bFMIUptzzXPzaPmtmkdDfw.png" alt="Image" width="618" height="445" loading="lazy">
<em>What is a component</em></p>
<h4 id="heading-so-what-is-a-module-really">So what is a module really?</h4>
<p>As mentioned, a module is a collection of components. If we have multiple components that communicate, or simply must be shown together in order to form an integrated whole, then you most likely need a module.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*c1vjeFupwd9ZTALYTluBSw.png" alt="Image" width="800" height="470" loading="lazy">
<em>What is a module</em></p>
<h4 id="heading-its-a-challenge-to-make-everything-reusable">Its a challenge to make everything reusable</h4>
<p>A principal engineer with over 30 years of experience in electrical engineering once said, we cannot expect everything to be reused because of time, cost and not everything is meant to be reused. It is better to reuse to some extent than expecting things to be reused 100%.</p>
<p>In general, it means that we don’t have to make everything reusable in the app. Some things are just meant to be used once. The rule of thumb is that if you need something more than two times, then maybe it is a good idea to create a module or a component.</p>
<p>At first, it may sound easy to make something reusable, but remember, it requires taking the component out from its environment, and expect it to work in another one. But often times, we have to have to modify parts of it to make it fully reusable, and before you know it, you’ve created two new components.</p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-es6-modules-and-why-theyre-important-a9b20b480773/undefined">Antoine</a>, wrote an article describing 3 essential rules of creating reusable JS components, which is recommend to read. When he presented VueJS to his team, an experienced coworker says:</p>
<blockquote>
<p>That’s great in theory, but in my experience these fancy “reusable” things are never reused.</p>
</blockquote>
<p>The idea is that, not everything should be reused, such as buttons, input-fields and check boxes and so forth. The whole job of making something reusable requires resources and time, and often we end up with over-thinking scenarios that would never occur.</p>
<p>The CEO of Stack Overflow, Joel Spolsky says:</p>
<blockquote>
<p>A 50%-good solution that people actually have solves more problems and survives longer than a 99% solution that nobody has because it’s in your lab where you’re endlessly polishing the damn thing. Shipping is a feature. A really important feature. Your product must have it.</p>
</blockquote>
<h3 id="heading-4-lets-build-a-dashboard-with-modules">4. Let’s build a dashboard with modules</h3>
<p>Now that we have a basic understanding of how modules work, let’s view a practical example you’ll most likely encounter when working with JS frameworks. We’ll be creating a simple dashboard following an architectural design that consist of layouts and components.</p>
<p>The code for the example can be found <a target="_blank" href="https://stackblitz.com/edit/modules-example">here</a>.</p>
<h4 id="heading-step-1-design-what-you-need">Step 1 — Design what you need</h4>
<p>In most cases, developers would jump directly into the code. However, design is an important part of programming and it can save you a lot of time and headache. Remember, design should not be perfect, but something that leads you to the right direction.</p>
<p>So this is what we need based on the architectural design.</p>
<ul>
<li><strong>Components:</strong> <code>users.js</code>, <code>user-profile.js</code> and <code>issues.js</code></li>
<li><strong>Layouts:</strong> <code>header.js</code> and <code>sidebar.js</code></li>
<li><strong>Dashboard:</strong> <code>dashboard.js</code></li>
</ul>
<p>All components and layouts will be loaded in <code>dashboard.js</code> and then we will bootstrap <code>dashboard.js</code> in <code>index.js</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*HMlBg4FARbr57a6Wrw2cYg.png" alt="Image" width="800" height="450" loading="lazy">
<em>Architectural design of our dashboard</em></p>
<p>So why do we have a layouts and components folder?</p>
<p>A layout is something that we need once, for instance a static template. The content inside the dashboard may change, but the sidebar and header will stay the same (and these are what is known as layouts). A layout can be either an error page, footer, status page and so forth.</p>
<p>The components folder is for general components we most likely will reuse more than once.</p>
<p>It is important to have a solid ground structure when dealing with modules. In order to effectively scale, folders must have reasonable names that make it easy to locate stuff and debug.</p>
<blockquote>
<p>Later I’ll show you how to create a dynamic interface, which requires having a folder space for the components and layouts we need.</p>
</blockquote>
<h4 id="heading-step-2-setup-folder-structure">Step 2— Setup folder structure</h4>
<p>As mentioned, we have 3 main folders: dashboard, components and layouts.</p>
<pre><code>- dashboard
- components 
- layouts
index.html
index.js ( entry point )
</code></pre><p>And in each file inside the folder, we <code>export</code> a <code>class</code>.</p>
<pre><code>- dashboard
    dashboard.js
- components
    issues.js
    user-profile.js
    users.js 
- layouts
    header.js
    sidebar.js
index.html
index.js ( entry point )
</code></pre><h4 id="heading-step-3-implementation">Step 3 — Implementation</h4>
<p>The folder structure is all set, so the next thing to do is to create the component (a <code>class</code>) in each file and then <code>export</code> it. The code convention is the same for the rest of the files: every component is simply a <code>class</code>, and a <code>method</code> that consoles “x component is loaded” where x is the name of the component in order to indicate that the component has been loaded.</p>
<p>Let’s create a user <code>class</code> and then <code>export</code> it as shown below.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Users</span> </span>{

  loadUsers() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Users component is loaded...'</span>)
  }

}

<span class="hljs-keyword">export</span> { Users };
</code></pre>
<p>Notice, we have various <a target="_blank" href="https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export">options</a> when dealing with the <code>export</code> statement. So the idea is that you can either <code>export</code> individual components, or a collection of components. For instance if we <code>export</code> the <code>class</code>, we can access the methods declared within by creating a new instance of the <code>class</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> { name1, name2, …, nameN };
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">FunctionName</span>(<span class="hljs-params"></span>)</span>{...}
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassName</span> </span>{...}
...

export * <span class="hljs-keyword">from</span> …;
<span class="hljs-keyword">export</span> { name1, name2, …, nameN } <span class="hljs-keyword">from</span> …;
<span class="hljs-keyword">export</span> { import1 <span class="hljs-keyword">as</span> name1, import2 <span class="hljs-keyword">as</span> name2, …, nameN } <span class="hljs-keyword">from</span> …;
<span class="hljs-keyword">export</span> { <span class="hljs-keyword">default</span> } <span class="hljs-keyword">from</span> …;
...
</code></pre>
<p>Alright, so if you look at the architectural diagram in step 1, you’ll notice that the <code>user-profile</code> component is encapsulated by the <code>header</code> layout. This means that when we load the <code>header</code> layout, it will also load the <code>user-profile</code> component.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { UserProfile } <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/users-profile.js'</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Header</span> </span>{

  loadHeader() {
    <span class="hljs-comment">// Creata a new instance</span>
    <span class="hljs-keyword">const</span> userProfile = <span class="hljs-keyword">new</span> UserProfile(); 

    <span class="hljs-comment">// Invoke the method (component)</span>
    userProfile.loadUserProfile();

    <span class="hljs-comment">// Output loading status</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Header component is loaded...'</span>)
  }

}

<span class="hljs-keyword">export</span> { Header };
</code></pre>
<p>Now that each component and layout has an exported <code>class</code>, we then <code>import</code> it in our <code>dashboard</code> file like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// From component folder</span>
<span class="hljs-keyword">import</span> { Users } <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/users.js'</span>;
<span class="hljs-keyword">import</span> { Issues } <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/issues.js'</span>;

<span class="hljs-comment">// From layout folder</span>
<span class="hljs-keyword">import</span> { Header } <span class="hljs-keyword">from</span> <span class="hljs-string">'../layouts/header.js'</span>;
<span class="hljs-keyword">import</span> { Sidebar } <span class="hljs-keyword">from</span> <span class="hljs-string">'../layouts/sidebar.js'</span>;


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dashboard</span> </span>{

  loadDashboard(){

    <span class="hljs-comment">// Create new instances</span>
    <span class="hljs-keyword">const</span> users = <span class="hljs-keyword">new</span> Users();
    <span class="hljs-keyword">const</span> issues = <span class="hljs-keyword">new</span> Issues();
    <span class="hljs-keyword">const</span> header = <span class="hljs-keyword">new</span> Header();
    <span class="hljs-keyword">const</span> sidebar = <span class="hljs-keyword">new</span> Sidebar();

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Dashboard component is loaded'</span>);
  }

}

<span class="hljs-keyword">export</span> { Dashboard }
</code></pre>
<p>In order to understand what is really going on in the <code>dashboard</code> file, we need to revisit the drawing in step 1. In short, since each component is a <code>class</code>, we must create a new instance and then assign it to an object. Then we use the object to execute the methods as shown in method <code>loadDashboard()</code>.</p>
<p>Currently, the app doesn’t output anything because we haven’t executed the method <code>loadDashboard()</code>. In order to make it work we need to <code>import</code> the <code>dashboard</code> module in file <code>index.js</code> like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Dashboard } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dashboard/dashboard.js'</span>; 

<span class="hljs-keyword">const</span> dashboard = <span class="hljs-keyword">new</span> Dashboard(); 

dashboard.loadDashboard();
</code></pre>
<p>And then the console outputs:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*XNy3aKKd_uVYy7O5zcgX3w.png" alt="Image" width="774" height="346" loading="lazy">
<em>ES6 Components loaded</em></p>
<p>As shown, everything works and the components load successfully. We can also go ahead and create two instances and then do something like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { Dashboard } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dashboard/dashboard.js'</span>; 

<span class="hljs-keyword">const</span> dashboard_1 = <span class="hljs-keyword">new</span> Dashboard(); 
<span class="hljs-keyword">const</span> dashboard_2 = <span class="hljs-keyword">new</span> Dashboard(); 

dashboard_1.loadDashboard();
dashboard_2.loadDashboard();
</code></pre>
<p>Which outputs the same as shown above, but since we have to new instances, we get the results twice.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*G4-R59VGgccpysU6nxs2dA.png" alt="Image" width="780" height="537" loading="lazy">
<em>Two unique instances of dashboard</em></p>
<p>In general, this allows us to easily maintain and reuse the module in the files needed without interfering with other modules. We just create a new instance which encapsulates the components.</p>
<p>However, as previously mentioned, the purpose was to cover the dynamic of how we can work with modules and components using the <code>import</code> and <code>export</code> statements.</p>
<p>In most cases when working with JS frameworks, we usually have a route that can change the content of the <code>dashboard</code>. Right now, everything along such as layouts is loaded every time we invoke the method <code>loadDashboard()</code> which is not an ideal approach.</p>
<h3 id="heading-5-optimization-techniques-for-dashboard-example">5. Optimization techniques for dashboard example</h3>
<p>Now that we have a basic understanding of how modules work, the approach is not really scalable or intuitive when we deal with large applications that consist of a lots of components.</p>
<p>We need something that is known as a dynamic interface. It allows us to create a collection of the components we need, and easily access it. If you are using Visual Studio Code, the IntelliSense shows you what components are available, and which one you’ve already used. It means you don’t have to open the folder/file manually to see what components has been exported.</p>
<p>So if we have a module with twenty components, we don’t want to <code>import</code> each component one line after the other. We simply want to get what we need, and that’s it. If you’ve worked with namespaces in languages such as C#, PHP, C++ or Java, you’ll notice that this concept is similar in nature.</p>
<p>Here’s what we want to achieve:</p>
<pre><code class="lang-js"><span class="hljs-comment">// FILE: dashboard.js</span>

<span class="hljs-comment">// From component folder</span>
<span class="hljs-keyword">import</span> { users, issues } <span class="hljs-keyword">from</span> <span class="hljs-string">'../components'</span>;

<span class="hljs-comment">// From layout folder</span>
<span class="hljs-keyword">import</span> { header, sidebar } <span class="hljs-keyword">from</span> <span class="hljs-string">'../layouts'</span>; 


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dashboard</span> </span>{

  loadDashboard(){

    <span class="hljs-comment">// Invoke methods</span>
    users.loadUsers();
    issues.loadIssues();
    header.loadHeader();
    sidebar.loadSidebar();

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Dashboard component is loaded'</span>);
  }

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">let</span> dashboard = <span class="hljs-keyword">new</span> Dashboard();
</code></pre>
<p>As shown, we have less lines of code, and we made it declarative without losing the context. Let’s see what changes we’ve made.</p>
<h4 id="heading-create-a-dynamic-interface-also-known-as-a-barrels">Create a dynamic interface (also known as a barrels)</h4>
<p>A dynamic interface allows us to create a collection of things we need. It’s like creating a toolbox with our favorite tools. One thing that is important to mention is that a dynamic interface should not be added in every single folder, but to folders that consist of many components.</p>
<blockquote>
<p>They greatly simplify the imports and make them look clearer. We just don’t want to have too many barrel files since that is counter productive and usually leads to <em>circular dependency</em> issues which sometimes can be quite tricky to resolve.   </p>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-es6-modules-and-why-theyre-important-a9b20b480773/undefined">Adrian Fâciu</a></li>
</ul>
</blockquote>
<p>In order to create a dynamic interface, we create a file named <code>index.js</code> which is located in the root of each folder to re-export a subset of files or components we need. The same concept works in TypeScript, you just change the type from <code>.js</code> to <code>.ts</code> like <code>index.ts</code>.</p>
<p>The <code>index.js</code> is the first file that loads when we access the root folder space — it’s the same concept as <code>index.html</code> that boots our HTML content. This means we don’t have to explicitly write <code>import { component } from './components**/index.js**'</code> <strong>,</strong> but instead <code>import { component } from './components</code>.</p>
<p>Here’s how a dynamic interface looks.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Root space -&gt; components folder</span>

<span class="hljs-comment">// Dynamic interface</span>
<span class="hljs-keyword">export</span> { users } <span class="hljs-keyword">from</span> <span class="hljs-string">'./users'</span>;
<span class="hljs-keyword">export</span> { issues } <span class="hljs-keyword">from</span> <span class="hljs-string">'./issues'</span>;
<span class="hljs-keyword">export</span> { userProfile } <span class="hljs-keyword">from</span> <span class="hljs-string">'./user-profile'</span>;
</code></pre>
<p>By using a dynamic interface, we end up with one less root level to access, and also less code.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Before</span>
<span class="hljs-keyword">import</span> { Users } <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/users.js'</span>;
<span class="hljs-keyword">import</span> { Issues } <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/issues.js'</span>;
<span class="hljs-keyword">import</span> { Header } <span class="hljs-keyword">from</span> <span class="hljs-string">'../layouts/header.js'</span>;
<span class="hljs-keyword">import</span> { Sidebar } <span class="hljs-keyword">from</span> <span class="hljs-string">'../layouts/sidebar.js'</span>;

<span class="hljs-comment">// After (with dynamic interface)</span>
<span class="hljs-keyword">import</span> { users, issues } <span class="hljs-keyword">from</span> <span class="hljs-string">'../components'</span>;
<span class="hljs-keyword">import</span> { header, sidebar } <span class="hljs-keyword">from</span> <span class="hljs-string">'../layouts'</span>;
</code></pre>
<h4 id="heading-create-a-new-instance-at-runtime">Create a new instance at runtime</h4>
<p>We removed the four instances in our <code>dashboard.js</code>, and instead created an instance at runtime when every component is exported. If you want to decide the name of the object, you can do <code>export default new Dashboard()</code>, and then <code>import dashView</code> without the curly braces.</p>
<pre><code class="lang-js"><span class="hljs-comment">// Before</span>
<span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> </span>{ dashboard }; 
<span class="hljs-keyword">const</span> dashboard = <span class="hljs-keyword">new</span> Dashboard(); 
dashboard.loadDashboard(); 

<span class="hljs-comment">// After</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> dashboard = <span class="hljs-keyword">new</span> Dashboard(); 
dashboard.loadDashboard()
</code></pre>
<p>As shown, we can directly invoke the method without needing to create a new instance, and also write less code. However, this is a personal preference and you can freely decide what is a practical use case for your app and requirements.</p>
<p>And finally, we load all components and layouts with one method.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { dashboard } <span class="hljs-keyword">from</span> <span class="hljs-string">'./dashboard/dashboard'</span>;

dashboard.loadDashboard();
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>I started with the intention of just showing a short example of how you can <code>import</code> and <code>export</code> a component, but then felt the need to share everything I know (almost). I hope this article provides you some insight into how to deal with ES6 modules effectively when building apps, and the things that are important in terms of separation-of-concerns (design principle).</p>
<h4 id="heading-the-takeaways"><strong>The takeaways:</strong></h4>
<ul>
<li>With ES6 modules we can easily reuse, maintain, separate and encapsulate components from being changed by external behavior</li>
<li>A module is a collection of components</li>
<li>A component is an individual block</li>
<li>Don’t try to make every everything reusable as it requires time and resources, and most often we don’t reuse it</li>
<li>Create an architectural diagram before diving into the code</li>
<li>In order to make components available in other files, we must first <code>export</code> and then <code>import</code></li>
<li>By using <code>index.js</code> (same concept for TypeScript <code>index.ts</code>) we can create dynamic interfaces (barrels) to quickly access the things we need with less code and fewer hierarchical paths</li>
<li>You can <code>export</code> a new instance at runtime by using <code>export let objectName = new ClassName()</code></li>
</ul>
<p>The good news is that things have changed and we are moving towards a component-based and reusable paradigm. The question is how can we reuse not only plain JS code, but HTML elements too in a practical and intuitive way. It looks like that ES6 modules combined with <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Web_Components">web components</a> may just give us what we need to build performant and scalable apps.</p>
<p>Here are a few articles I’ve written about the web-ecosystem along with personal programming tips and tricks.</p>
<ul>
<li><a target="_blank" href="https://medium.freecodecamp.org/a-comparison-between-angular-and-react-and-their-core-languages-9de52f485a76">A comparison between Angular and React</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/a-chaotic-mind-leads-to-chaotic-code-e7d6962777c0">A chaotic mind leads to chaotic code</a></li>
<li><a target="_blank" href="https://codeburst.io/developers-that-constantly-want-to-learn-new-things-heres-a-tip-7a16e42302e4">Developers that constantly want to learn new things</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/learn-these-core-javascript-concepts-in-just-a-few-minutes-f7a16f42c1b0?gi=6274e9c4d599">Learn these core Web Concepts</a></li>
<li><a target="_blank" href="https://medium.freecodecamp.org/7-javascript-methods-that-will-boost-your-skills-in-less-than-8-minutes-4cc4c3dca03f">Boost your skills with these important JavaScript methods</a></li>
<li><a target="_blank" href="https://codeburst.io/learn-how-to-create-custom-bash-commands-in-less-than-4-minutes-6d4ceadd9590">Program faster by creating custom bash commands</a></li>
</ul>
<p>You can find me on Medium where I publish on a weekly basis. Or you can follow me on <a target="_blank" href="http://twitter.com/dleroari">Twitter</a>, where I post relevant web development tips and tricks along with personal dev stories.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Let’s get classy: how to create modules and classes with Python ]]>
                </title>
                <description>
                    <![CDATA[ By Hari Santanam In object-oriented computer languages such as Python, classes are basically a template to create your own objects. Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and function... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/lets-get-classy-how-to-create-modules-and-classes-with-python-44da18bb38d1/</link>
                <guid isPermaLink="false">66c35a66cf1314a450f0d722</guid>
                
                    <category>
                        <![CDATA[ class ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ modules ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 15 Nov 2018 20:47:24 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*0PG2toS66TDJQQ7AtHGJ-Q.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Hari Santanam</p>
<p>In object-oriented computer languages such as Python, classes are basically a template to create your own objects. Objects are an encapsulation of variables and functions into a single entity. Objects get their variables and functions from classes.</p>
<p>Say what?</p>
<p>Here are some examples that will help you understand — read on. There is also an interactive code shell, simply press the “Run” button at the top of the specific window.</p>
<p>The simplest way to describe classes and how to use them is this:</p>
<p>Imagine you have great powers. You create a species (“class”).</p>
<p>Then you create attributes for that species (“properties”) — height, weight, limbs, color, powers, and so on.</p>
<p>Then you create an instance of that species — Fido the dog, Drogon from Game of Thrones, and so on. Then you work with these instances:</p>
<ul>
<li>In a game, for instance, they would engage in action, interact, using their attributes.</li>
<li>In a banking app, they would be the different transactions.</li>
<li>In a vehicle buy/sell/trade/lease app, the vehicle class could then spawn sub-classes such as cars. Each would have attributes such as mileage, options, features, color, and trim.</li>
</ul>
<p>You can already see why this is useful. You are creating, re-using, adapting, and enhancing items in a very efficient, logical, and useful way.</p>
<p>By now, you have probably realized that this is a way to classify and group, one that that is similar to how humans learn:</p>
<ul>
<li>Animals are living things that are not human or trees, in a basic sense</li>
<li>then you move on to different types of animals — dogs, cats are probably the first animals most of us learnt about</li>
<li>then you move to different attributes of animals — shapes, sizes, sounds, appendages and so on.</li>
</ul>
<p>For instance, when you were a child, your first understanding of a dog was probably something with four legs that barked. Then you learnt to distinguish that some were real dogs, others were toys. That this “dog” concept contained many types.</p>
<p>Creating and using classes is basically:</p>
<ul>
<li>building a template to put “things” in — a classification</li>
<li>which can then be operated on. For example, pulling up all the people with dogs that you could request to link to a blog on pets, or all bank clients who might be good prospects for a new credit card.</li>
</ul>
<p>The main point here is <strong>classes</strong> are objects that can produce instances of those templates, on which operations and methods can be applied. It is an excellent way to conceptualize, organize, and build a hierarchy for any organization or process.</p>
<p>As our world gets more complex, this is a way to mimic that complexity from a hierarchical perspective. It also builds a deeper understanding of the processes and interactions for business, technical, and social settings from a virtual information technology point.</p>
<p>An example might be a video game you create. Each character could be a “class”, with its own attributes, that interacts with instances of other classes. King George of the “King” class might interact with Court Jester Funnyman of the “Clown” class, and so on. A King might have a royal “servant” class, and a “servant” class would always have a “King” class, for example.</p>
<p>This is what we will do:</p>
<ul>
<li>create a class and use it</li>
<li>create a module and move the class creation and initiation to the module</li>
<li>call the module in a new program to use the class</li>
</ul>
<p>The code is available in GitHub <a target="_blank" href="https://github.com/HariSan1/class-module">here</a>.</p>
<pre><code>#TSB - Create Class <span class="hljs-keyword">in</span> Python - rocket positions (x,y) and graph
</code></pre><pre><code>#some items and comments bolded to call attention to processimport matplotlib.pyplot <span class="hljs-keyword">as</span> plt
</code></pre><pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rocket</span>():  <span class="hljs-title">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-title">self</span>, <span class="hljs-title">x</span></span>=<span class="hljs-number">0</span>, y=<span class="hljs-number">0</span>):    #each rocket has (x,y) position; user or calling <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">has</span> <span class="hljs-title">choice</span>    #<span class="hljs-title">of</span> <span class="hljs-title">passing</span> <span class="hljs-title">in</span> <span class="hljs-title">x</span> <span class="hljs-title">and</span> <span class="hljs-title">y</span> <span class="hljs-title">values</span>, <span class="hljs-title">or</span> <span class="hljs-title">by</span> <span class="hljs-title">default</span> <span class="hljs-title">they</span> <span class="hljs-title">are</span> <span class="hljs-title">set</span> <span class="hljs-title">at</span> 0    <span class="hljs-title">self</span>.<span class="hljs-title">x</span> = <span class="hljs-title">x</span>    <span class="hljs-title">self</span>.<span class="hljs-title">y</span> = <span class="hljs-title">y</span>      <span class="hljs-title">def</span> <span class="hljs-title">move_up</span>(<span class="hljs-params">self</span>):    <span class="hljs-title">self</span>.<span class="hljs-title">y</span> += 1      <span class="hljs-title">def</span> <span class="hljs-title">move_down</span>(<span class="hljs-params">self</span>):    <span class="hljs-title">self</span>.<span class="hljs-title">y</span> -= 1      <span class="hljs-title">def</span> <span class="hljs-title">move_right</span>(<span class="hljs-params">self</span>):    <span class="hljs-title">self</span>.<span class="hljs-title">x</span> += 1      <span class="hljs-title">def</span> <span class="hljs-title">move_left</span>(<span class="hljs-params">self</span>):    <span class="hljs-title">self</span>.<span class="hljs-title">x</span> -= 1</span>
</code></pre><pre><code>#Make a series <span class="hljs-keyword">of</span> rockets - x,y positions, I am calling it rocketrockets=[]rockets.append(Rocket())rockets.append(Rocket(<span class="hljs-number">0</span>,<span class="hljs-number">2</span>))rockets.append(Rocket(<span class="hljs-number">1</span>,<span class="hljs-number">4</span>))rockets.append(Rocket(<span class="hljs-number">2</span>,<span class="hljs-number">6</span>))rockets.append(Rocket(<span class="hljs-number">3</span>,<span class="hljs-number">7</span>))rockets.append(Rocket(<span class="hljs-number">5</span>,<span class="hljs-number">9</span>))rockets.append(Rocket(<span class="hljs-number">8</span>, <span class="hljs-number">15</span>))  #Show on a graph where each rocket is
</code></pre><pre><code><span class="hljs-keyword">for</span> index, rocket <span class="hljs-keyword">in</span> enumerate(rockets):  #original position <span class="hljs-keyword">of</span> rockets  print(<span class="hljs-string">"Rocket %d is at (%d, %d)."</span> % (index, rocket.x, rocket.y))  plt.plot(rocket.x, rocket.y, <span class="hljs-string">'ro'</span>, linewidth=<span class="hljs-number">2</span>, linestyle=<span class="hljs-string">'dashed'</span>, markersize=<span class="hljs-number">12</span>)  #move the <span class="hljs-string">'rocket'</span> one up  rocket.move_up()  print(<span class="hljs-string">"New Rocket position %d is at (%d, %d)."</span> % (index, rocket.x, rocket.y))  #plot the <span class="hljs-keyword">new</span> position  plt.plot(rocket.x, rocket.y, <span class="hljs-string">'bo'</span>, linewidth=<span class="hljs-number">2</span>, linestyle=<span class="hljs-string">'dashed'</span>, markersize=<span class="hljs-number">12</span>)  #move the rocket left, then plot the <span class="hljs-keyword">new</span> position  rocket.move_left()  plt.plot(rocket.x, rocket.y, <span class="hljs-string">'yo'</span>, linewidth=<span class="hljs-number">2</span>, linestyle=<span class="hljs-string">'dashed'</span>, markersize=<span class="hljs-number">12</span>)
</code></pre><pre><code>#show graph legend to match colors <span class="hljs-keyword">with</span> positionplt.gca().legend((<span class="hljs-string">'original position'</span>,<span class="hljs-string">'^ - Moved up'</span>, <span class="hljs-string">'&lt; - Moved left'</span>))plt.show()#plt.legend(loc=<span class="hljs-string">'upper left'</span>)
</code></pre><p><img src="https://cdn-media-1.freecodecamp.org/images/1*HVwrF6BepYaTcRAltJaPDQ.jpeg" alt="Image" width="555" height="580" loading="lazy">
<em>Output from code above, using Python class</em></p>
<p>Now let us create a module and move some of the code above to the module. Any time we need to create this simple set of x,y coordinates in any program, we can use the module to do so.</p>
<h3 id="heading-what-is-a-module-and-why-do-we-need-it">What is a module and why do we need it?</h3>
<p>A module is a file containing Python definitions and statements. Module is Python code that can be called from other programs for commonly used tasks, without having to type them in each and every program that uses them.</p>
<p>For example, when you call “matplotlib.plot”, you are calling a package module. If you didn’t have this module you would have to define the plot functionality in <strong>every</strong> program that used a plot graph.</p>
<p>From the Python <a target="_blank" href="https://docs.python.org/2/tutorial/modules.html">documentation</a>:</p>
<blockquote>
<p>If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead.This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.</p>
<p>To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).</p>
</blockquote>
<p>Here’s our simple module. It takes the class creation and the functions to move an instance of that class from the program above and into its own class. We will then use this in a new program simply by calling and referencing this module:</p>
<p>Notice what we did above:</p>
<ul>
<li>created and initialized the class</li>
<li>created a function to move an instance of the class in the four major directions (up, down, right, left) and the increments — as parameters, or arguments to the function</li>
<li>created another function to calculate the distance between two instances of the class, using the graph distance formula</li>
</ul>
<p>Here’s how we will use the new module to re-write the same program from the first part. Notice in the import section at the beginning, we now import the <code>simple_module1</code> module that we just created:</p>
<p>Here’s the output from the code using our module. Note that they are the same, except for the chart title and the shape of the position markers, which I changed for comparative purposes.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*M5O4PXU-UqHuXe62qSPezg.jpeg" alt="Image" width="576" height="588" loading="lazy">
<em>Output from code from creating and calling our own module!</em></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*-Ihrh85VkkfYuZhiH_4oAg.png" alt="Image" width="800" height="371" loading="lazy">
<em>Comparison of the original file-left(create class, use it) and same functionality using a module, right</em></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*QnBS_HmigffIj6PBz2DvUQ.jpeg" alt="Image" width="800" height="179" loading="lazy">
<em>Comparison of the output. On the right side, I change the marker shape for distinction, but the positions are unchanged.</em></p>
<p>That’s great, you may say — what are some other uses for this? One classic example is a bank account. A customer class might contain the name and contact details and — more importantly — the account class would have deposit and withdrawal elements.</p>
<p>This is grossly oversimplified but, for illustrative purposes, it is useful. That’s it — create a template, then define instances of that template with details (properties), and add value by adding, subtracting, modifying, moving, and using these instances for your program objectives.</p>
<p>Still wondering about classes? Ok, let’s get “classy” — here’s another simple illustration. We will call this class “Person”. It has only two properties — name and age. We will then add an instance of this with a person’s name and age, and print it. Depending on what your objective is, you can imagine all the other details you might add — for example, marital status and location preferences for a social networking app, job experience in years and industry specialization for a career related app. Press the little triangle below to see it work.</p>
<p>So there you have it. You can create many different classes, with parent classes, sub-classes and so on. Thanks for reading — please clap if you liked it. Here are some other references if you would like to learn more:</p>
<ul>
<li><a target="_blank" href="https://docs.python.org/3/tutorial/classes.html">Python documentation — Classes</a></li>
<li><a target="_blank" href="https://www.tutorialspoint.com/python/python_classes_objects.htm">Python Object Oriented — Tutorials Point</a></li>
<li><a target="_blank" href="https://www.learnpython.org/en/Classes_and_Objects">Classes and Objects — learnpython.org</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
