javascript

How to Use Import and Export in JavaScript


One of the greatest features of ES6 is the ability to export and import the javascript modules. Before ES6, importing modules could be included in a script by using the require() function.  ES6 introduced the import and export keywords which bring Javascript more in line with programming languages like Java.

Exporting Modules

ES6 modules are stored in files. There is only one module per file and one file per module. There are two different types of export, named and default

Named Export

A module can export multiple things by prefixing its declarations with the keyword export. This type of exports are distinguished by their names and are called named exports:


//-------util.js------
export function addTwoNumbers(x,y){
  return x + y
}
export let students = ['wisdom','bill','fred','grim']

Default Export

This type of export can only export a single functionality.Here you are only able to export only a single function, objects, or primitive values but you can use the different name to import.

//----myFunction.js ----
export default function () {
  alert("Hello Default Export")
}

Note that you can have more than one default export in a module.Instead use the Named Export type.Also note that exporting without the default keyword means we will have to use braces to import the file.

Importing Modules

To import a module into a script, you can use the import keyword.Using the named export example ,we can import the module like this:

//----main.js---
import { addTwoNumbers, students } from 'util';

Here we are explicitly bringing in the function and variable. We could import the whole module and refer to its named exports via property notation:

import * as util from 'util';

console.log(util.addTwoNumbers(2,13))
console.log(util.students)

The pattern here is quite simple import * as name from "module-name"
Note that you have to leave out the curly braces to import the default export.

import myFunction from 'myFunction'

Conclusion

Using the Es6 module help to organize your codes and make your work look neat. You can export and import functionalities to test and also sharing of data is made easy.


Share on social media

//