Building Modular JavaScript Application with ES6 Module System

February 09, 2018 0 Comments

Building Modular JavaScript Application with ES6 Module System



Over time, JavaScript has been lacking module system. This led to "unofficial" community-based standards like CommonJs modules and Asynchronous Module Definition, the AMD, standards as well as coding patterns like the Immediately Invoked Function Expression(IIFE) playing key roles in packaging JavaScript code. Talking about a module, it is basically a way of organizing code into a single unit, making them consumable by other pieces of code. Having a single unit to handle a single responsibility of your entire project is a great way to go. It keeps things simple and easy to test. One of the key concepts that encouraged the adoption of previous modules systems and coding patterns is the ability to hide information by not publicly exposing implementation details and avoiding global variables.

ES6 module feature helps to attain the same benefits as the previous module systems and patterns, just that we now have a native feature and standard. Let's write our first module.

From the above code, we created a js file that exports a class. We can even export functions, values, objects. Also, we exported the class with the default keyword, which is one method. We can export without using the default keyword. Either of these has its own way of importing the exported information. Now let's import the information we exported.

In case, we omit the default keyword, then, the syntax will differ.

Explore further on Js modules with this section of explorejs and a talk from Kent C. Dodds;

Tag cloud