ES6 Modules

Overview

Javascript was mostly used for functional programming. If we ever wanted to make the code modular we had to separate the code in different files and load them as scripts.

With ES6 it is now possible to import the code from one file to another as Modules. Modules are javascript files that can be loaded in a different mode. This was necessary because modules have different semantics.

Advantages of using modules

  • Module codes always run in strict mode.
  • Variables created inside the module are module scoped only. They are never added to the global scope.
  • Value of this in top level module is undefined.
  • Module should export the code inorder to make it accessible.
  • Module can import another modules as well.

The real power of modules is the ability to export and import only bindings you need, rather than whole code.

Exporting Modules

Basic Exporting

//export properties
export var name = 'Prashant Yadav';
export let age = 23;
export const nationality = 'Indian';

//export methods
export function add(num1, num2){
  return num1 + num2;
}

//export class
export class Addition{
    constructor(num1, num2){
       this.num1 = num1;
       this.num2 = num2;
    }

    add(){
        return this.num1 + this.num2;
    }
}

//This is private as we are not export it
let rectangle = (width, height) => {
    return width * height;
}

let square = (length) => {
    return rectangle(length, length);
}

//exporting square separately
export { square };

There are a few things you should remember while exporting the modules.

  • You can export as many modules as you want from a single file.
  • function and class names should be specified if you are not exporting them as default.
  • There can be only one default module exported.

Exporting Default Module

The default value for a module is a single variable, function or class specified by the default keyword.

//exporting anonymous function
export default function(num1, num2){
   return num1 + num2;
}

//exporting anonymous class
export default class{
   constructor(num1, num2){
       this.num1 = num1;
       this.num2 = num2;
   }

   add(){
      return this.num1 + this.num2;
   }
}

//exporting named function
let add = function(num1, num2) => {
   return num1 + num2;
}

export default add;
//    OR
export {add as default}

//exporting multiple values
export let name = 'prashant';
export let age = 23;
export default function(name, age){
   return `${name} is ${age} years old`;
}

Renaming export modules

We can rename the module name while exporting them.

//exporting named function
let add = function(num1, num2) => {
   return num1 + num2;
}

export {add as sum};

Importing Modules

When we import the module the binding to which we assign the values act as const variable. We cannot re declare them and/or use them as variables, function, class.
Note: ./, /, ../ indicates the directory listing. Use them accordingly to find your files.

Basic Importing

//import single
import { add } from './module.js';

console.log(add(1, 2)); // 3

Importing multiple modules

//import multiple
import { name, age } from './module.js';
console.log(name, age);
// 'Prashant', 23

Import all modules

//import all the modules
import * from './module.js'
console.log(name, age);
console.log(add(1,2));
// 'Prashant', 23
// 3

Note! we cannot change the value of imported binding directly. We have to do it explicitly through the imported module.

//export data
export name = 'prashant';
export function updateName(val){
   name = val;
}

//import data
import {name, updateName} from './example.js';
console.log(name); //prashant
updateName('pranav');
console.log(name); //pranav
name = 'sachin';  //syntax error

Importing default modules

we can give any name to default modules

//importing default modules
import sum from './example.js'

//Exporting multiple values with one default value
export let name = 'prashant';
export let age = 23;
export function(name, age){
  return `${name} is ${age} years old.`;
}

import display, {name, age} from './modules.js';
//   OR
import {display as default, name, age} from './modules.js';

console.log(display(name, age));
//"prashant is 23 years old"

Renaming import modules

We can rename the module name while importing them.

//Renaming modules while importing
import {sum as add} from './example.js'

Re-exporting imported modules

we can re-export the imported modules.

//Basic
import { add } from './modules.js';
export { add }

//In single line
export { add } from './modules.js';

//Renaming and exporting
export { add as sum } from './modules.js';

//Exporting all modules
export * from './modules.js';

Loading modules in browser

Evan before ES6 browsers hand different ways to import files.

  • Load different files with script element and src.
  • Embedding inline code with script element and without src.

But browsers have now updated themselves to handle the modular code.
We can use type attribute to use the import and export.

//load the file
<script src="modules.js" type="module"></script>

//load the inline script
<script type="module">
import { add } from './modules.js';

console.log(add(1, 2));
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *