Understanding the imports and exports of JavaScript ES6

javascript es6 : import - export

 

 

JavaScript ES6 supports for exporting and importing functions, variables from one module to another. There are two kinds of exports: A named export and a default export.

Named Export:

In JavaScript ES6, Named export are used to export multiple things from a module by adding the keyword export to their declaration. These exports are distinguished by their names. While importing these named functions or variables, one can use the same name to refer to these corresponding functions or variables.

Consider the following example. I have created the named functions in a JavaScript file called functionsFile.js.

//exporting a function
export function squareNumber(x) {
  return x * x; 
}

//exporting a variable 
export var pi = 3.14; 



//Another way of named export: 



//exporting a function
function squareNumber(x) {
  return x * x; 
}

//exporting a variable 
var pi = 3.14; 

export {squareNumber, pi} ; 

 

 

Now the function squareNumber and the variable pi are ready for import. I will create a file called main.js and import the above exported values.

//main.js 


import {squareNumber, pi} from "functionsFile"; 

var radius = 7; 
console.log("Area of a circle is", pi * squareNumber(7)); 


//Another way of importing 

import * as mathFuncs from "functionsFile"; 
console.log("Area of circle is ", mathFuncs.pi * mathFuncs.squareNumber(7)); 

 

Default Export

Default export in Javascript ES6 permits only a single default export per module. A default export can be for a function, class or an object. The default export is accomplished as follows:

//functionsFile.js

export default function(x) { 
  return x * x ; 
}

 

Then in another file, it is straightforward to import the default export.

//main.js 

import squareNumber from "functionsFile"; 
squareNumber(7);

 

Exporting a class

In Javascript ES6, classes can also be exported like functions. An example of that is shown below:

//MyClass.js 

export default class MyClass {
  ...
} 


//Main.js

import MyClass from "MyClass";

 

If this example is considered in React, where the MyClass is a component and needs to be rendered inside the Main, it will look as follows:

//MyClass.js 

import React from "react"; 
export default class MyClass extends React.Component {
  ...
} 


//Main.js

import React from "react"; 
import MyClass from "MyClass";

export default class Main extends React.Component {
  render() {
    return(
        <MyClass />
      );
  }
}

 

It should also be noted that you cannot conditionally import or export things. One cannot nest import and export inside a block.