How to Import JavaScript Module: Syntax, Usage, and Examples

While developing a JavaScript application, you must have gone through situations where you needed to import functionality from another module. You may have wondered about the different ways you can import a module in JavaScript. Here comes this tutorial.

In this tutorial, we will explore the methods of importing a module, including various import statements, their usage, and examples. Understanding module import is a fundamental aspect of modern JavaScript development. So, let’s dive deep into the content to gain in-depth knowledge of module imports.

Why Importing Modules?

An import statement in JavaScript is used when you want to import or want to use bindings that exist in some other file or module. 

We just cannot have an application written within a single file. Hence, we must export parts of our code and use them in different modules/files by importing them. It is easier to understand, manage and debug bite-sized and separated code rather than boatloads of it altogether in a single file ending up in a never-ending scroll! That’d be a nightmare! The core idea behind this import feature is to keep files compact and focus on minimal tasks and components at a time.

Traditional Module Syntax vs ES6 Module Syntax

In pre-ECMAScript 6 (ES6), JavaScript primarily used the built-in ‘require’ module to import files and module.exports or exports to export chunks of your code. 

With the introduction of ES6, import for importing modules and export or export default for exporting modules have become standard syntax.

The idea, however, is the same. But ES6 module syntax gives us a more standardized and clear way of accomplishing this.

Note: The JavaScript file that you are trying to import, must have a declaration type = ‘module’ in order to inform the browser that the script used should be treated as an ES6 module.

Read More: Explaining the Ultimate Difference Between Node.js require vs ES6 import

JavaScript Import Syntaxes

Below are the many import syntaxes provided by the Official MDN Docs. These vary depending on the contents we’re importing from a module.

import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
const promise = import("module-name");

Parameters:

  • defaultExport: Refers to the name that will indicate the default export from the module.
  • module-name: Refers to the file/module to import from. This could be a relative or an absolute path of the .js file which will consist of our module. Make sure you only use single or double-quoted strings here.
  • name: Refers to the name of the module object. This will be more like a namespace when the imports are referred.
  • exportN: Refers to the specific exports you want to import.
  • aliasN: Refers to the name of the named imports.

Dynamic Import:

In the above syntaxes, the last one, import(“module-name”) is the dynamic import syntax. With the dynamic import, you do not need your scripts to be a type = ‘module’. Dynamic import is used in situations when you want to import a module based on a condition or on demand.

Among all the syntaxes mentioned, you can choose the one that suits your needs and give you the required output. Let’s now look at some examples in the next section to understand how each can be used.

JavaScript Import Examples

Let’s now see examples of importing modules using different JS import syntaxes.

Importing the Entire Contents of a Module

import * as sampleModule from '/modules/sample-module.js';

This will insert sampleModule into the current scope and will contain all the exports from the module in the file located in the path: /modules/sample-module.js.

Also, accessing exports refers to using the module name, ‘sampleModule’ as a namespace. For instance, sampleModule exports giveMeANumber(), we may then call it like this:

sampleModule.giveMeANumber();

Importing a Single Export from a Module

import {sampleExport} from '/modules/sample-module.js';

Here the sampleExport object or value is imported from sample-module.js and can be used within the current module.

Importing Multiple Exports from a Module

import {carrotRecipes, beetRecipes} from '/modules/sample-module.js';

This will import both carrotRecipes and beetRecipes into the current scope.

Importing an Export with a More Convenient Alias

import {whyIsThisSoLongModuleExportName as cuteName} from '/modules/sample-module.js';

This is how you can rename an export while importing it. 

Rename Exports while Importing

import {
  whyIsThisSoLongModuleExportName as cuteName,
  thisIsStillLongModuleName as short
} from '/modules/sample-module.js';

In this way, we can rename multiple exports while importing, with convenient aliases.

Importing a Module for its Side Effects

You only want the side-effects of an entire module, but don’t want to import it. See the below examples.

import '/modules/sample-module.js';

This will just run the global code of the module and won’t actually import any values!

You may also use it with dynamic imports:

(async () => {
  if (thisIsTrue) {
    // import module just for side effects
    await import('/modules/sample-module.js');
  }
})();

Importing Defaults

You might have a default export such as an object, a class, a function, etc. The import statement will help you import your defaults easily.

The simplest and direct way to import defaults:

import customDefault from '/modules/sample-module.js';

We may also make use of the syntaxes we had a look at a while ago. Make sure you declare the default import first.

import customDefault, * as sampleModule from '/modules/sample-module.js';
// sampleModule shall be used as a namespace

OR

import customDefault, {carrotRecipes, beetRecipes} from '/modules/sample-module.js';
// specific, named imports

When you want to import a default export using dynamic imports, this will be a bit different. You must first destructure the default and rename the “default” key from the returned object.

(async () => {
  if (thisIsTrue) {
    const { default: customDefault, carrotRecipes, beetRecipes } = await import('/modules/sample-module.js');
  }
})();

Dynamic Imports

In situations when you wish to import conditionally or on-demand, you may use dynamic import. To do this, you have to use the import() function. This will then return a promise.

import('/modules/sample-module.js')
  .then((module) => {
    // Your custom function.
  });

This form is also compatible with the await keyword.

const module = await import('/modules/sample-module.js');

Conclusion

ES modules provide an official, standardized module system for JavaScript. Being a JavaScript developer, we frequently used imports more than in other programming languages. With ES modules, importing the necessary exports becomes effortless and allows us to import them according to our preferences.

Comparing JavaScript require vs import, the latter grants the ability to restructure exports and import them based on our needs, greatly aiding in the development of complex applications.

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Aneesha S
Aneesha S
Articles: 173