For a developer, It's necessary to write the code in such a way so that it can be easily readable and testable. It becomes very important when you are working on large projects.
It should always be a habit from the fresher level to write code more reusable, which means the code should be split into separate independent functions/modules. This way life can be easier when you proceed to the complex level of the project.
Javascript provides options to make this task very easy with the help of import and export statements.
The import statement is used to import bindings exported by another module. It enables us to use the functions defined in the second/imported module.
import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name"; var promise = import("module-name");
defaultExport: This is used to import a module that is default exported from the imported module. With it no need to put the name inside curly braces.
module-name: This is the name of the module from where the module has to import.
name: This is the name of the module object that will be used as a kind of namespace to refer to the imports.
exportN: Name of the exports to be imported.
aliasN: Names that will refer to the named imports.
This statement is used we want created javascript module to export functions, primitive values, or object so that they can be used by other modules of the program with the import statement
Exporting a module(compute.js)
In the above example, two functions has been defined which performs a different task. At the bottom, these method has been assigned to module.exports to make it available where ever it would be called.
Importing a module(compute.js)
At the top we can see module has been imported using require keyword with its relative path as argument. In javascript frontend frameworks like Angular, React import statement is used for importing
In this article, We learn about the basics of import and export statement which is very important for the developers who are working in javascript environment or freshers in javascript.
I hope the article was helpful to you.
Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.
Thanks!