How to Import Modules in JavaScript

The “import” keyword in JavaScript is part of the ES6 (ECMAScript 2015) used to include functions, objects, or values from other modules into your current module or script. This is beneficial for code organization, separation of concerns, and reusability.

Syntax

The syntax of the import module is the following.

It has many variations because it depends on whether we import single or multiple contents from a file.

import defaultExport from 'module_name';
import * as name from 'module_name';
import { content } from 'module_name';
import { content as alias } from 'module_name';
import { content , content2 } from 'module_name';
import { content , content2 } from "module-name/path/to/specific/un-exported/file";
import { content , content2 as alias2 , [...] } from 'module_name';
import defaultExport, { content [ , [...] ] } from 'module_name';
import defaultExport, * as name from 'module_name';
import 'module_name';

var content = import('module_name');

The name parameter is the “module object” which will be used as a namespace to refer to the exports.

The export parameters specify individually named exports, while the import * as name syntax imports all of them. Below are examples to clarify the syntax.

Example

Create a project folder, and inside the project folder, create three files.

  1. app.js
  2. data.js
  3. start.js

Now, node.js does not support import-export Functionality by default. So, we need a babel transpiler to make it work. 

We need to install two packages for that. So go to the terminal and type the following command to generate the package.json file.

npm init -y

Then we need to install two node modules. So type the following command.

npm install babel-register babel-preset-env --save-dev

It will install the modules inside the node_modules folder.

Now, write the following code inside the start.js file.

require('babel-register')({
 presets: ['env']
});

module.exports = require('./app.js')

We will run this file to run the import-export statement in the app.js file.

The next step is to write the following code inside the data.js file.

export const add = (x, y) => {
 return x + y
}

The add() function accepts the parameters, adds them, and returns the result.

Here the syntax is ES6, and we have used the arrow function.

Finally, add the following code inside the app.js file.

import { add } from './data';

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

Here, we have imported the data module and the specific add function from that module.

Now, run the start.js file and see the output.

node start.js

Javascript Import Statement Tutorial

We have imported a single export from a module in the above example.

If we have multiple export modules, then we can import various modules.

Some practical use cases of JavaScript import

Loading module on demand

The import keyword may be called the function to import the module dynamically. When used this way, it returns the promise.

let app = await import('./data');
console.log(`The addition is: ${add(2, 3)}`);

It will give the same output. In the above code, we have used an async-await feature of ES7.

If you are new to that, then check out this article.

Loading modules based on conditions

When you place the import() function inside the conditional statement, such as if-else, you can load modules based on a specific condition.

if (condition) {
  import('./moduleA.js')
    .then((moduleA) => {
    moduleA.functionInModuleA();
  })
  .catch((err) => {
    console.error(`Error loading moduleA: ${err}`);
  });
} else {
  import('./moduleB.js')
    .then((moduleB) => {
       moduleB.functionInModuleB();
    })
   .catch((err) => {
     console.error(`Error loading moduleB: ${err}`);
   });
}

Computed module specifiers

A computed module specifier means that you’re dynamically constructing the string that specifies the module to import, often based on some condition or variable value.

let data = `message_${getData()}.js`;

import(info)
  .then(...);

Import Multiple Modules in Javascript

We will create another module inside the data.js file.

export const add = (x, y) => {
  return x + y
}

export const subtract = (x, y) => {
  return x - y;
}

Now, import both of the modules inside the app.js file.

import { add, subtract } from './data';

console.log(`The addition is: ${add(2, 3)}`);
console.log(`The suntraction is: ${subtract(21, 19)}`);

Finally, run the start.js file and see the output.

Javascript Import Statement Tutorial With Example

Import with a more convenient alias

You can rename an export when importing it. For example, this inserts sub into the current scope.

See the app.js file. We have renamed the module subtracts to the sub.

import { add, subtract as sub } from './data';

console.log(`The addition is: ${add(2, 3)}`);
console.log(`The suntraction is: ${sub(21, 19)}`);

Importing defaults in Javascript

Let’s say; we only have one export default module inside the data.js file.

const add = (x, y) => {
   return x + y
}
export default add;

In the above code, we have used the export default keyword, which means we only export the add module from this file.

Now, if we have one default module inside a data.js file, we can import it inside the app.js file like below.

import add from './data';

console.log(`The addition is: ${add(2, 3)}`);

See the output below.

Importing defaults

Import *

Usually, we list what to import in curly braces import {…}.

Create one file called client.js and add the following code.

const marvel = (hero) => {
 console.log(`Hello, ${hero}!`);
}

const dc = (hero) => {
 console.log(`Bye, ${hero}!`);
}

export {marvel, dc};

The client.js file exports two functions. So, we can import both functions inside the app.js file.

Now, add the following code inside the app.js file.

import * as superHeros from './client';

superHeros.marvel('Venom');
superHeros.dc('Wondar Woman');

So we have imported all the modules as superHeros.

See the output.

Hello, Venom!
Bye, Wondar Woman!

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.