Updated April 15, 2023
Introduction to ES6 modules
ES6 stands for the ECMAScript Standard 6th edition, which involves adding a series of features to the existing JavaScript programming language. Module system present in javascript helps in inculcating the features and code available in directories and files and also making sure at the same time that another can easily access one piece of code as per requirement. Furthermore, the package managers help in the installation of tools and software that will suffice high-level dependencies. In this article, we will generally look at what ES6 module of JavaScript is, how it can be used, exports available in ES6, and classification of modules in ES6.
What is ES6 module?
ES6 module consists of the file that contains the javascript code in it. It does not contain the module keyword or use strict keywords in it and can be read as a simple script file. What makes the ES6 module different from usual script files is that the strict mode is automatically kept on by default, and we don’t need to explicitly mention the same. The other difference is that there is an inbuilt functionality to import and export the modules.
By default, whatever is declared in the module remains local and private. In order to make it public, we can export the feature so that other modules can use it. This can be done by using one of the simple methods of using the export keyword for the same. The export functionality is available for the class, let, function, const, or var included in top-level functions. We can write the usual code of javascript that includes the arrays and objects used on a global level and web-related objects like XMLHttpRequest and document. We can even make use of the other functions in a separate file and later import them into the module and use them.
Importing all the required files and their functions can be done at the top of the module by adding the import statement. When you are using import, the loading of all the imports is done, and then the execution of the body of the module is done in the depth-first traversal manner as in dependency graphs. While doing so, if there are any cycles, they are avoided, and the code that is already executed is skipped.
How to use ES6 Modules (code)
ES6 Modules can be used if you have a compiler installed on your systems, such as Babel or Traceur. You can refer to the link for the complete reference and guidance on how to use ES6 using compilers. In addition, you can write your own code using the ES6 terminologies such as import and export statements, variable declaration using let, var keywords, and use some looping statements such as for loop and template strings.
Let us consider this small code snippet that makes the use of ES6 Generator and creates a function named createValue –
Function* createValue(begin, end, incrDecr){
For (var sample = begin; sample < end; sample += incrDecr ){
Yield sample;
}
}
// Using the created function
for( var demo of createValue(100,199,10)){
var educbaDiv = $('<div>').attr ( 'class', 'color').css({background-color: '#${demo}'}).append (‘demo code in hexa decimal: #${demo}’);
content$.append ( educbaDiv);
}
}
The output of printing the above values while executing the code is as shown in the below image –
Default exports
We can use the export default for any object literal, function, value, or class we want. Consider that while the new standards are created to enable interoperability and the existing AMD and CommonJS. Consider that we are working on the Node project, and we have installed the npm lodash by using the command npm install lodash. When we are using it in our ES6 module code, we can make use of the functions present in lodash by simply importing them by using the below import statement –
Import {educbaSampleFunc1, educbaSampleFunc2, each} from lodash;
// use the above, imported functions.
Suppose that by mistakenly, you made the use of _.each and want to continue using it that way instead of each or perhaps make the use of the underscore _ symbol as the name of the function as it is required in lodash then you can make certain small changes in the import statement as import _ from lodash that stands for import default as _ from lodash.
The AMD and CommonJS modules are present in the ES6 module by default and are available in default export and are equivalent to what we retrieve by using the require() function inside the module, which results in the exports object.
We can export several things at the same time in ES6 modules. However, it is only in the case of CommonJS that we get only the default exports.
If you need to have your own default export in your module of ES6, then it’s quite easy. You just have to export the variable or object that you have created in your program at last as a default thing. For example, refer to the following code snippet –
Let educbaObj = {
SampleField : sampleValue,
educbaField:educbaValue
}
Export { educbaObj as default};
Or the above code snippet also has a shortcut, and the following alternative code snippet can be used for the same –
Export default {
SampleField : sampleValue,
educbaField:educbaValue
};
Es6 modules classified
ES6 modules are classified into two categories as mentioned below –
- Default Exports: When we need to export only a single value from the module, we can use default export. We can only write one default export statement within a single module.
Let us consider one example to understand the steps required to perform default export –
Step 1
We will create a file named educba.js and will have the following code in it –
Let sampleName = 'Educba'
Let organization = {
getOrganization : function(){
return organization
},
setOrganization : function(updatedName){
organization = updatedName
}
}
Export default organization
Step 2
We will create a new file named myOrganization.js and will import the educba.js into it.
Import sample from './educba.js'
Console.log(sample.getOrganization())
Sample.setOrganization('Educba Organization')
Console.log(sample.getOrganization())
Step 3
We will now execute the es6 module created by us using HTML. We will create a new HTML file and mention the attribute type =”module.” The file will look as shown below –
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="./ myOrganization.js" type="module"></script>
</body>
</html>
The output of the above code will be as shown below –
- Named Exports : They are identified from their names, and we can export multiple named export statements from a single module.
The same steps as that of default export will be performed for named exports as well.
Step 1
Create a file named educba.js
let organization = "Educba"
let getOrganization = function(){
return organization.toUpperCase()
}
let setOrganization = function(updatedName){
organization = updatedName
}
export {organization,getOrganization,setOrganization}
Step 2
Create a new file organization.js
import {organization,getOrganization} from './educba.js'
console.log(organization)
console.log(getOrganization())
Step 3
Create an HTML file to render the output –
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="./organization.js" type="module"></script>
</body>
</html>
The output of the above code is –
Conclusion
We can use ES6 modules to extend the functionality in the javascript programming language and import and export the components within the module. For example, we can make use of the functionalities such as for loops, variables, let, and var statements by exporting them in ES6 modules.
Recommended Articles
This is a guide to es6 modules. Here we discuss the ES6 module of JavaScript, how it can be used, exports available in ES6, and classification. You may also have a look at the following articles to learn more –