0% found this document useful (0 votes)
11 views9 pages

ES6 Module Exports and Imports Guide

JavaScript modules allow developers to organize code into reusable pieces that can be imported and exported. ES6 modules support named and default exports, enabling the sharing of functions, classes, and variables across different files. Additionally, ES6 handles cyclic dependencies by sharing bindings rather than values, allowing for more flexible module interactions.

Uploaded by

shubrattporwal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views9 pages

ES6 Module Exports and Imports Guide

JavaScript modules allow developers to organize code into reusable pieces that can be imported and exported. ES6 modules support named and default exports, enabling the sharing of functions, classes, and variables across different files. Additionally, ES6 handles cyclic dependencies by sharing bindings rather than values, allowing for more flexible module interactions.

Uploaded by

shubrattporwal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript Modules

Modules are the piece or chunk of a JavaScript code written in a file. JavaScript
modules help us to modularize the code simply by partitioning the entire code into
modules that can be imported from anywhere. Modules make it easy to maintain the
code, debug the code, and reuse the piece of code. Each module is a piece of code that
gets executed once it is loaded.

Modules in ES6 is an essential concept. Although it is not available everywhere, but


today we can use it and can transpile into ES5 code. Transpilation is the process of
converting the code from one language into its equivalent language. The ES6 module
transpiler tool is responsible for taking the ES6 module and converts it into a
compatible code of ES5 in the AMD (Asynchronous module definition is a
specification for the JavaScript programming language) or in the CommonJS style.

During the build process, we can use Gulp, Babel, Grunt, or other transpilers for
compiling the modules. The variables and functions in a module are not available for
use unless the file exports them.

Exporting and Importing a Module

Exporting a Module

JavaScript allows us to export a function, objects, classes, and primitive values by


using the export keyword. There are two kinds of exports:

o Named Exports: The exports that are distinguished with their names are
called as named exports. We can export multiple variables and functions by
using the named export.
o Default Exports: There can be, at most, one value that can be exported by
using the default export.

Importing a Module

To import a module, we need to use the import keyword. The values which are
exported from the module can be imported by using the import keyword. We can
import the exported variables, functions, and classes in another module. To import a
module, we simply have to specify their path.

When you import the named export, you must have to use the same name as the
corresponding object. When you import the default export, we can use any name of
the corresponding object.

Let us elaborate on these exports and imports.

Named Exports and Imports


Named exports are distinguished with their names. The class, variable, or any
function which is exported by using the named export can only be imported by using
the same name.

Multiple variables and functions can be imported and exported by using


the named export.

Syntax

Let us see the syntax to use named export in class, function, or in a variable. Below
we are showing how to individually export the class, variable, and function by using
the named export.

1. //Named export in class


2. class Nokia{
3. //properties
4. //methods
5. }
6. export {Nokia}; //Named export
7.
8. //Named export in functions
9. function show(){
10. }
11. export {show};
12.
13. //Named export in Variables
14. const a = 10;
15. export {a};

We can apply more than one named export in a module. We can use the syntax of
multiple named exports in a module as follows:

[Link]

1. class Nokia{
2. //properties
3. //methods
4. }
5. function show(){
6. }
7. const a = 10;
8. export {Nokia, show};

Let us see how to import the named exports.


Importing the Named export

To import the bindings that are exported by another module, we have to use the
static import statement. The imported modules are always in the strict mode,
whether we declare them in strict mode or not.

Syntax

[Link]

1. import {Nokia, show} from './[Link]';

Importing all

If we want to import all of the export statements simultaneously, then we can import
them individually.

But it will be hard when we have so many named exports. So, to make it easier, we
can do it as follows:

1. import * as device from './[Link]'; // Here, the device is an alias, and [Link] is t
he module name.

Suppose, we have defined a class Nokia in the module [Link], and if we want to
use it then by using the alias, we can perform it as:

1. [Link] //if we have a class Nokia


2. [Link] // if we have a function show
3. device.a // if we have a variable a

Let us try to understand the Named export and import within a single example.

We have to make two JavaScript modules to perform export and import. In the first
module, we export the class, function, and variable. In the second module, we will
import them by using the named import.

Example - Named Export and Import

Here, we are creating two JavaScript modules in which the first JavaScript module
is [Link], and the second module name is [Link]. We are also creating
an HTML file [Link]. Then, we will execute this .html file in the server.

Next, we have to manually link the JavaScript file in the HTML file by using the src
attribute in the <script></script> tag. But the module still will not work. To enable
the module, we have to use the type = "module" in the <script></script> tag.

[Link]
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
7. <script type = "module" src = "[Link]"></script>
8. <title>Document</title>
9. </head>
10. <body>
11. <h1>ES6 Modules import and export</h1>
12. </body>
13. </html>

[Link]

1. class Display{
2. show(){
3. [Link]("Hello World :)");
4. }
5. }
6. function javaT(){
7. [Link]("Welcome to javaTpoint");
8. }
9. export {Display,javaT};

[Link]

1. import {Display,javaT} from "./[Link]";


2. const d = new Display();
3. [Link]();
4. javaT();

Output

Run the above [Link] file in the live server. Then, open the terminal in the
browser by using ctrl+shift+I. After the successful execution, you will get the
following output:
Default Exports and Imports

We can have only one default export in a module. A default export can be imported
with any name.

Syntax

Let us see the syntax to use default export in class, function, or in a variable. Below
we are showing how to individually export the class, variable, and function by using
the default export.

Unlike the named export, we cannot simultaneously make more than


one export statement in default export.

1. //Default export in class


2. class Nokia{
3. //properties
4. //methods
5. }
6. export default Nokia; //Default export
7.
8. //Deafult export in functions
9. function show(){
10. }
11. export default show;
12.
13. //Default export in Variables
14. const a = 10;
15. export default a;

Importing the Default export


To import the bindings that are exported by another module, we have to use the
static import statement. The imported modules are always in the strict mode,
whether we declare them in strict mode or not.

ADVERTISEMENT
ADVERTISEMENT

Syntax

[Link]

1. class Nokia{
2. //properties
3. //methods
4. }
5. export default Nokia;

[Link]

1. import Nokia from './[Link]';

Example - Default import and export

[Link]

1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
7. <script type = "module" src = "[Link]"></script>
8. <title>Document</title>
9. </head>
10. <body>
11. <h1>ES6 Modules import and export</h1>
12. <h2>Default import and export</h2>
13. </body>
14. </html>

[Link]
1. class Display{
2. show(){
3. [Link]("Hello World :)");
4. [Link]("Default Import and Export Example");
5. }
6. }
7. export default Display;
[Link]

1. import Display from "./[Link]";


2. const d = new Display();
3. [Link]();

Output

Run the above [Link] file in the live server. Then, open the terminal in the
browser by using ctrl+shift+I. After the successful execution, you will get the
following output:

ES6 Cyclic dependencies

Cyclic dependency is a direct or indirect relation between two or more modules that
depend on each other. Such modules are known as the mutually recursive modules.

The modules in ES6 automatically supports the cyclic dependencies. Two modules,
such as A and B, are cyclically dependent on each other if both A imports B and B
imports A either transitively or indirectly.

Suppose we have three modules named A, B, and C. Their chain of dependencies is


like A->B->C->A, i.e., A is dependent upon B; B is dependent upon C and C is
dependent upon A.

CommonJS and some of the other libraries support the circular dependencies, but
there is a problem with importing and using named exports from a circular
dependent module.

ES6 solves this problem by sharing the bindings to the values rather than the values
itself in the exports. It means the connection with the variables declared in the body of
the module can be done. We can see the demonstration for the same in the following
code:

Example

[Link]

1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
7. <script type = "module" src = "[Link]"></script>
8. <title>Document</title>
9. </head>
10. <body>
11. <h1>ES6 Cyclic dependencies</h1>
12. </body>
13. </html>

[Link]

1. export let count = 0;


2. export function show() {
3. count++;
4. }

[Link]

1. import { show, count } from './[Link]';


2. [Link](count);
3. show();
4. [Link](count);

Output

Common questions

Powered by AI

Transpilation involves converting ES6 module code into a format compatible with older JavaScript environments, such as ES5. Tools like Babel are used in combination with build systems like Gulp or Grunt to automate this process. The transpiler translates modern syntax and features into equivalent code that can run in environments that don't support ES6 modules natively. This enables developers to write using modern standards while maintaining compatibility across different platforms .

`export * as alias` syntax should be used when a module has numerous exports that need to be imported simultaneously into another module. This syntax allows the developer to create an alias for the entire module, facilitating access to its exports without having to individually import each one, thus improving readability and maintainability when dealing with large sets of exports .

To enable ES6 module functionality within an HTML document, the script must be included using the `<script type="module">` attribute. This attribute informs the browser that the script is a module, which supports import/export functionality. Additionally, when referencing the module in the HTML, the source file paths must be correctly specified to ensure seamless integration during execution .

In ES6, named exports allow multiple values to be exported from a module, and they must be imported using their exact exported names. In contrast, default exports allow only one export per module and can be imported under any name. Named exports provide flexibility for exporting multiple bindings simultaneously, while default exports simplify imports and allow a single primary export to be emphasized .

Cyclic dependencies occur when two or more modules depend on each other, directly or indirectly. This can create issues with named exports, as previous JavaScript specifications and some libraries like CommonJS faced difficulties in resolving such dependencies. ES6 addresses this by sharing the bindings to values, not the values themselves, ensuring modules can reference each other's exports without execution order issues. It helps maintain module relationships consistent through late binding, preventing runtime errors .

The `import` statement in ES6 serves both named and default imports efficiently. Named imports require exact binding names, allowing multiple imports directly mapped to their export names, beneficial for explicitness and modular code design. Default imports allow developers to import a singular main export from a module under any desired name, providing flexibility in encapsulating primary functionalities. This dual facility allows for a varied module design strategy, promoting both specificity and simplicity, enhancing code organization and potential readability .

In the example provided, there are two JavaScript modules, `Mobile.js` and `App.js`. `Mobile.js` exports a class `Display` and a function `javaT`. These are named exports. In `App.js`, the `Display` class and `javaT` function are imported using the `import {Display, javaT} from './Mobile.js';` syntax. Then in `App.js`, an instance of `Display` is created, and both the `show` method of `Display` and the `javaT` function are executed, demonstrating how named exports and imports are utilized .

The significance of ES6 modules supporting cyclic dependencies lies in their ability to handle mutual module dependencies without causing errors typically associated with named exports. Named exports in cyclic dependencies often lead to unresolved symbols due to the order of import execution. By supporting late binding and sharing the bindings rather than values themselves, ES6 resolves identifiers correctly, even in complex dependency chains, ensuring functional module cooperation and execution order is correctly managed .

ES6 ensures that imported modules operate in strict mode by default, which enforces a stricter parsing and error handling of JavaScript code. This prevents several common bugs and unsafe actions such as accidental creation of global variables. By automatically opting into strict mode, ES6 modules inherit the benefits of this stricter environment, promoting better practices and more secure code .

ES6 modules help in organizing JavaScript code by allowing developers to split it into reusable, maintainable parts. This modularization makes the code easier to debug, maintain, and reuse because each module can be developed independently and imported where needed. Additionally, specialists can use transpilers like Babel to convert ES6 modules into a compatible format for environments only supporting ES5 .

You might also like