Table of contents
No headings in the article.
To start with, let's understand what the Javascript Module is and what it is not, the Javascript module is nothing but another Javascript statement, expressions, functions, javascript variables, or just any valid Javascript code you can think of that can be found within a regular Javascript file. The difference here is that before any Javascript file can be considered or used as a module, it must exist within a javascript environment that supports the use of modules. it could be within a nodeJs environment which is a runtime environment that allows developers to write Javascript code on the server or within any Javascript library/framework.
Javascript makes use of two important keywords to achieve this which are export and import Javascript keywords.
To export javascript modules we have two ways of achieving that which are named export and default export.
The code snippet below is an example of a named exported module.
// myDateTime.js
const myDateTime = () => new Date()
export { myDateTime, name }
Here my myDateTime is the name of the function within this file myDateTime.js
This code snippet here is an example of a default exported Javascript module.
// myDateTime.js
const myDateTime = () => new Date()
export default myDateTime
Here my myDateTime is the name of the function within this file myDateTime.js
Importing an exported Javascript module is very simple depending on how the module was exported.
If the module was exported as a default module you can use the below code snippet to import it.
Importing myDateTime as a default exported Javascript module
import myDateTime from './myDateTime.js'
// Using the module in myDtateTime.js file
console.log(myDateTime())
Here my myDateTime() is a function within the myDateTime.js file.
Importing myDateTime.js as a named exported module, look at the code snippet below.
import { myDateTime } from './myDateTime'
// Using the module in myDateTime.js file
console.log(myDateTime())
Here my myDateTime() is a function within the myDateTime.js file.
Conclusion: Here talked about Javascript modules and different ways we can export them so that we can use them in other files where we will be importing them, I hope you find value.