Writing JavaScript Modules ( An ECMAScript 2015 )

I am a BIG fan of "App Modularization". I find it much fun and productive to modularize your app's architecture. JavaScript being the MOST expensive block of any web app, this makes sense.

Modules in javascript allow you to split JavaScript Apps up into separate chuncks that can be imported when needed.

Modern Browsers now support module functionality natively - browsers can optimize loading of modules, making it more efficient than having to use a library to achieve the same.

Why modules?

  1. Maintainability
  2. Resusabaility
  3. Perfomance
  4. Productivity

Using Modules ( Export and Import )

export : is used to expose public variables, objects, classes and functions.

 // Add.js
    const Add = () {
       return a + b;
    }
    
    export { Add }

import : is then used to pull items from a module into another script or module.

 // App.js
    import { Sum } from './Add.js';
    console.log( Add(1, 2) ); // 3

Advanced Recipe

A single export statement can be used as shown below.

 export { Add, Subtract };

A single import statement can be used as shown below for all public items.

 import { Add, Subtract } from './Calculator.js';

Or use export as you declare a function, an object, a class or a variable.

 // export a function
   export const Add = () {
     return a + b ;
   }
   
   // an object
   export let person = {
      name : "Maye Edwin",
      age : 18
   }

   // or a variable
   export let name = `Maye Edwin`;

Or use as and * to import all exports from a given module.

 import * as App from './Calculator.js';
    
      // using each import e.g
      App.Add(4, 5);
      App.Divide(3, 2);

Or use as to import an export or exports from a given module (helps to prevent naming problems).

 import { user as Bio } from './Users.js';
 import { sum as Add, product as Multiply } from './Calculator.js';

Using ES6 Modules

All module import scripts must be loaded by setting a type="module" attribute in the script tag.

  <script type="module" src="./App.js"></script>

Remix this Project on Glitch and take up the challenge 👷

Add subtraction, multiplication and division modules to this app! Good luck!

Got any question? You wanna have a chat? Hit my inbox on twitter asap 😉