So you are thinking about what is Module & what it does?
Here’s the answer…. If you have a complex app and you have to scroll through hundreds or thousands of lines of code, then the job of debugging or just understanding the app becomes very much harder. Javascript helps us out with this by having ‘imports’ and ‘exports’.
It basically means that the sharing of code between multiple files. A ‘module’ in Javascript can be thought of as a container that holds related code which can then be exported to another file.
It basically has two main keywords :
export : keyword labels variables and functions that should be accessible from outside the current module.
import : keyword allows the import of functionality(variables and functions) from other modules.
Benefits of using modules
Maintainability: A well-designed module aims to lessen the dependencies on parts of the codebase as much as possible so that it can grow and improve independently.
Reusability: In programming, reusable code is the use of a similar code in multiple functions. No, not by copying and then pasting the same code from one block to another and from there to another and so on. Instead, code reusability defines the methodology you can use to use similar code, without having to re-write it everywhere.
Modules in Practice
With the help of Modules, we can use the features of one file into another file. Suppose you have two JavaScript files & you have to import and export variables & functions between them.
1. Importing/Exporting the Single Variable:
File-one: exporting the variable to file-two
File-two: importing the variable from file-one
2. Importing/Exporting multiple Variables or Functions:
File-one: exporting multiple variables or functions to file-two
File-two: importing multiple variables or functions from file-one
3. Importing/Exporting Default value(it should be single):
File-one: exporting Default variable or function to file-two
File-two: importing Default variable or function from file-one
4. Importing everything (*) at once:
File one: exporting multiple variables or functions to file-two
File-two: importing everything from file-one at once(here * denotes everything)
5. Importing /Exporting with an alias(another name):
File-one: We can give aliases to exported members with the 'as' keyword
File-two: We can also give aliases to imported members with the 'as' keyword
So, This is the basic introduction of JavaScript Modules. I hope I am able to make some of your points clear.
Hope you have enjoyed this and gain something from it. Waiting for your feedback. ✔
Follow me on Twitter — @javascript_bug to check out my other cool posts.
Happy Coding! 💻 😀
Top comments (2)
Thank you Suhel. This is good.
Also you can write the
export
keyword before the function or variable name in the source file.for example:
The same would apply to variables too.
Thank you so much, sir