Hey reader👋Hope you are doing well😊
In the last post we have discussed about modules in NodeJS. In this post we are going to an another way of using modules in NodeJS.
So let's get started🔥
Importing a Module
In the last post we have discussed that everything in NodeJS is a module and we can use any module using require()
method. Now instead of using this old school methodology for using modules let's explore a new method of using a module in file.
With the release of ES6 (6th edition of the ECMAScript language) the standardized syntax for importing and exporting modules in JavaScript was also released.
Using import
we can use any module in a file. Though NodeJS doesn't directly support the ES6 import
directly.
There are two ways of using import
in NodeJS-:
- Modifying
package.json
file-:
We can modify the package.json
file in order to use import
in NodeJS.
Let me explain you what package.json is-:
package. json
is a metadata file in a NodeJS project that describes the project's dependencies, scripts, configuration, and other details. It typically contains information about the project such as its name, version, author, and license. It also lists the project's dependencies on other Node.
You can easily create package.json
file by using command-:
npm init
.
To use import
in NodeJS add following lines to package.json
-:
"type":"module"
Now let's use module in script.js
using import
-:
- By using esm module-:
We can install esm module using command-:
npm install esm
ECMAScript Modules (ESM) is a specification for using Modules in the Web. It's supported by all modern browsers and the recommended way of writing modular code for the Web.
Using esm it is not needed to add "type":"module"
in package.json
, we can directly use import
statement.
Advantages of using import
import
helps in selectively loading the pieces of code that are required which helps in saving memory.So we don't need complete module here we only import those functionalities which are required.In case of
require
loading is synchronous whereasimport
can be asynchronous so it performs better than required.
Quick Tip!
You also have to modify your custom module also as follows-:
exports
will not going to work here.require
was a method defined in CommonJS andimport
in ES6.
So this was all about import
. I hope you have understood this blog. In the next blog we are to read about REPL. Till then stay connected and don't forget to follow me.
Thankyou🤍
Top comments (2)
Thanks so much. So the best is to focus on es6 ?
Yes