Javascript - Module Modules Importing

Introduction

Once a module with the relevant exports is set up, it can be accessed inside another module by using the import keyword.

There are two parts to an import statement:

  • the identifier you're importing and
  • the module from which those identifiers should be imported.

This is the statement in its basic form:

import { identifier1, identifier2 } from "./moduleFile.js"; 

identifier1 and identifier2 are the bindings imported from moduleFile.js.

The module is specified via the path to the file containing the module after the from keyword.

Using the above syntax, you can import specific bindings from a module as follows,

Suppose we have the following moduleFile.js

export function add(a, b) { 
    return a + b; 
} 
function multiply(a, b) { 
    return a * b; 
} 
export { multiply }; 

importing the functions sum and multiply

import { sum, multiply } from "./moduleFile.js"; 
console.log(sum(1, 7));                // 8 
console.log(multiply(2, 3));           // 6 

Here, there are two bindings imported from the moduleFile module: sum and multiply can be used like locally defined identifiers.

To import all the exports available in the module without having to explicitly declare them by name, use the wildcard *.

// import everything 
import * as example from "./moduleFile.js"; 
console.log(example.sum(1,7));          // 8 
console.log(example.multiply(2, 3));    // 6 

Here, all exported bindings in moduleFile are loaded into an object called example.

Irrespective of the number of times the module is imported in the import statements, it will only be executed once.

Related Topics