Currently most of the client side web applications are using one or the other JavaScript framework or library such as React JS, Angular or Vue JS. While working with these frameworks, most of the JavaScript developers must have come across different types of imports in their applications.

In React JS, we see the following type of imports quite commonly

import React, {useState} from ‘react’

 

In Angular, it can be like this

import { FormsModule, ReactiveFormsModule } from “@angular/forms”;

 

We may find imports like this as well

import * as $ from ‘jQuery’;

So, what is the difference between these imports ? Which type of exported values we are importing with the above imports ?

Modules are one of the very important and widely accepted functionality introduced in ES6 JavaScript. A Module is nothing but a JavaScript file (js file) containing some code. All variables, constants, functions, classes defined inside that file are private to that module unless exported using the export keyword.

We can export variables, constants, functions and classes by using the export or export default keywords.

Named Exports

The variables or constants or functions or classes exported with the keyword export are called as Named Exports. The term ‘Named Export’ is because, we need to import these variables using their same name in other modules.

example:

moduleone.js

Copy to Clipboard

 

moduletwo.js

Copy to Clipboard

 

In the above example, we have used the same exported variable names when we imported them in another module.

If we want, we can also rename the variable names while importing by using as keyword.

example:

moduletwo.js

Copy to Clipboard

Import all named exports

If a module is exporting several members of that file, we can import all of them from another module by using *  as syntax.

example:

moduletwo.js

Copy to Clipboard

Default Exports

Instead of using normal export keyword, we can also use export default syntax to export any one member of the module file. We can export only one member by using the export default syntax. Unlike named exports where we need to use the exact name of the variable to import (for that reason, we need to remember the names of the exported variables ), we can use any name to import the variable which was exported by default.

example:

moduleone.js

Copy to Clipboard

 

moduletwo.js

Copy to Clipboard

 

Mixing Named & Default Exports

One module can also contain several named exports along with a default export. We see this pattern commonly in React JS

example:

moduleone.js

Copy to Clipboard

 

moduletwo.js

Copy to Clipboard

 

Importing All Named & Default Exports

Similar to the way we imported all named exports using * as syntax, we can import all named and default exported members by using the same * as syntax. But, to access the default exported member, we need to use the default property on the imported variable name.

example:

moduletwo.js

Copy to Clipboard