JavaScript Import Export Tutorial with Examples

Last updated on by Digamber
I am glad to have this chance to share with you today about the JavaScript Import and Export statement. The import statement is used to import bindings that are exported by another JavaScript file.

Code manageability is the most import factor in web development. If you are building an application that has a large codebase, it isn’t very easy to manage that codebase.

Ordinarily, you have to scroll through hundreds or maybe thousands of lines of code, and this makes the process of debugging very difficult.

How about? We assign one task to only one function and keep some of the functions in one file (component).

Luckily, JavaScript has a solution to this problem in the form of imports and exports statements.

Modules in JavaScript are the small block of codes that are a reusable piece of code that are used to create a JavaScript application. Same way, you write some of the functions in one file, and JavaScript import lets you share all the functions via that module file with various other JavaScript files.

Import Syntax in JavaScript

The following are the syntax for importing the files in JavaScript. Given below, import syntaxes are based on the importing condition as per single or multiple files requirement.

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

defaultExport – It’s a name that refers to the default export statement from the module.

name – The name value is the name of the module object that is described to be used as a kind of namespace to refer to the imports.

module-name – This is the module from where the module has to import from.

dataN – This is the name of the exported that has to be imported.

aliasN – Names that belong to the named imports in Javascript.

JavaScript Import Example

I would like to begin by creating a js-imports-example project directory and generate three files in it for JavaScript import and export statement examples.

  • app.js
  • run.js
  • data-module.js

Next, run the command to generate the package.json file inside the project folder.

npm init -y

Next, install the babel-register and babel-preset-env plugins as a dev dependency. These plugins add the import and export support in our node.js project.

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

The above command creates the node_modules folder and installs both of the plugins inside of it.

Next, open the run.js file and add the following code in it.

// run.js

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

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

The require hook help binding itself to node’s require statement and automatically compile files on the fly.

In the next step, we are going to create a JavaScript module file and add some data in the data-module.js file.

// Data-module.js

export const calculateCircumference = ((radius) =>  {
    return 2 * Math.PI * radius;
})

Here we defined the small function to calculate the circumference of a circle using the Math.PI method.

We initialized this module using the export const statement. By doing this, we can easily export this class throughout our JavaScript application. This small function is useful in getting the radius of a circle and takes the numerical value as an argument.

If you have noticed, we have used the es6 syntax to create the es6 modules in our data-module.js file.

Now, let’s add the data inside the app.js file and learn how to import variable from another file in JavaScript.

// app.js

import { calculateCircumference } from './data-module';

console.log(calculateCircumference(2))

We import the data-module file and particular calculateCircumference() method from the particular module.

Let’s run the following command to run the code and check out the result for import and export functionality.

node run.js
# Output

12.566370614359172

Import Multiple Modules in JavaScript

So far, we have learned how to import a single module now we are going to look at how to export multiple modules and then import multiple modules in JavaScript.

Go to the data-module.js file and define the other modules in the particular file.

// Data-module.js

export const calculateCircumference = ((radius) =>  {
    return 2 * Math.PI * radius;
})

export const toCelsius = ((f) => {
    return (5/9) * (f-32);
})

We created another function that converts from Fahrenheit to Celsius.

Next, import both of the modules in the app.js file as given below.

// app.js

import { calculateCircumference, toCelsius } from './data-module';

console.log(calculateCircumference(2))

console.log(toCelsius(77))

Then, run the `node run.js` command from your terminal to get the result for the above imports.

# node run.js

12.566370614359172
25

JavaScript import an export Modules as alias

JavaScript allows us to rename an export, especially when we are importing it from another file. For instance, we give the tc alias to the toCelsius module.

// app.js

import { toCelsius as tc } from './data-module';

console.log(tc(77))

// Result => 25

As you can see we converted toCelsius to tc and it is working absolutely fine.

JavaScript Dynamic Imports

Dynamic imports is beneficial in the scenario where you need to load a module conditionally and on-demand. The static form is favoured for initial loading dependencies.

import('/modules/module-file.js')
  .then((module) => {
    // module response.
});

The import keyword may be called as the method to import a module dynamically. It returns a promise when used as given above.

Dynamic imports also support the ES await keyword.

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

Importing defaults in JavaScript

Let’s assume we have got the only one export default function or module available within the data-module.js file.

// data-module.js

const calculateCircumference = ((radius) =>  {
    return 2 * Math.PI * radius;
})

export default calculateCircumference;

In the given code, we have defined the export default keyword, which means we are exporting the calculateCircumference function from the data-module.js file.

Now, importing defaults is left to be done, we have got the single default module inside the data-module.js file. It can be imported inside the main app.js file as given below.

// app.js

import calculateCircumference from './data-module';

console.log(calculateCircumference(2))

// Result => 12.566370614359172

JavaScript Import *

Ordinarily, we create a list of what to import in curly braces import {…}, like this:

Open the data-module.js file, add the following code in it.

// data-module.js

const calculateCircumference = ((radius) =>  {
    return 2 * Math.PI * radius;
})

const toCelsius = ((f) => {
    return (5/9) * (f-32);
})

export {calculateCircumference, toCelsius};

We are exporting two modules from data-module file, now we will learn to import both of these modules in app.js file.

Open the app.js file and include the following code inside of it.

// app.js

import * as math from './data-module';

math.calculateCircumference(2)
math.toCelsius(77)

Using import * as in JavaScript allow us to import all the modules at once.

Check out the output for the above code.

# node run.js

12.566370614359172
25

Conclusion

In this tutorial, we have learned following types of import and export.

Import:

Named exports from module:
import {x [as y], …} from “module”

Default export:
import x from “module”
import {default as x} from “module”

Everything:
import * as obj from “module”
Import the module, but do not assign it to a variable:
import “module”

Export

Before declaration of a class/function/…:
export [default] class/function/variable …

Standalone export:
export {x [as y], …}.

Re-export:
export {x [as y], …} from “module”
export * from “module” (doesn’t re-export default).
export {default [as y]} from “module” (re-export default).

So in this tutorial, we have learned how to use JavaScript export statements, import statements, dynamic module imports, JavaScript Import * and Importing defaults.

We have tried to shed light on almost every topic. However, you are willing to know more about JavaScript imports statement then do visit MDN.

Finally, we have completed JavaScript Import and Export tutorial with examples.

Digamber
Digamber

Digamber Rawat is from Dev Bhoomi Uttarakhand, located in northwestern part of India. He is a Data Scientist by profession and a primary author of this blog.