Node.js Require vs Import
Overview
While importing packages in the Node.js project, you may have come across the two keywords i.e., require and import. Well, both keywords are used to import packages or modules in the Node.js project. But there are certain differences between them.
Introduction
Let's first understand modules in Node.js. Modules are blocks of code that are encapsulated in single or multiple files to facilitate related functionality to the application. Modules break down the complex long piece of code into smaller parts for easy debugging and management. Modules also help in the re-usability of code.
Node.js has mainly two module systems:
- CommonJS modules and
- ECMAScript modules.
CommonJS is the default module system.
Node.js has three types of modules:
- Core Modules:
These are built-in modules like: http, fs, etc. - Local Modules:
These modules are locally created by the programmer. - Third-Party Modules:
These modules are available to use after installation using NPM(Node Package Manager) like: express, mongoose etc.
Now Let's look into the different ways to include these modules in our application:
Require in Node.js
As discussed above that Node.js follows the CommonJS module system, and the built-in require function is the easiest way to include modules in this system. When we call require in Node.js then the require function first reads a JavaScript file, executes that file, and then the require function proceeds to return the exports object.
When require function is invoked Node goes through the following sequence of steps:
- Resolving:
In this step Node gets the absolute path of the module. It follows the following steps to resolve the path:- For const test = require('example') syntax:
- It first looks for core modules with that name.
- If no such core module is present then it looks for a file with the name node_modules/ of the current folder and still if no module is found then it will look for it in the parent folders of the current folder.
- If a folder is found with that name containing an index.js file then that index.js file is loaded.
- For syntax with path starting with ./ or ../ like: const test = require('./lib/example.js') :
- Such syntax may contain an absolute path or a relative path. So the file present at that location is loaded in this case.
- For const test = require('example') syntax:
Note: If no file is found after these steps then an error is thrown.
- Loading:
In this step Node loads the module and determines the type of file content. - Wrapping:
After loading, the module code is wrapped in a special function that will give access to a couple of objects. It also gives a separate scope to the variables. - Evaluating:
At this step JavaScript Engine (usually V8) executes the code present in the wrapper function and exports functions or variables mentioned with the module.exports in the file. - Caching:
After the evaluation step, Node.js modules are cached (i.e., stored for future use) when the module is loaded for the first time. And later if you need to load the same node module next time then node.js does not go through above mentioned steps for that module again as it will copy that module from the cache.
Syntax and Examples for Require in Node.js
Loading core modules
Syntax:
Example:
Loading local modules
For loading locally created modules, we can provide a path to the required function in the following ways.
Using absolute path
Syntax:
Example:
Using relative path
We can also provide a relative path using ./ or ../ in the required function.
Syntax:
Example:
Note:
You can omit the .js extension in the above example also i.e. if you don't provide any extension then Node searches for a file with that module_name and .js extension and loads it.
Using folder path
You can load modules just by folder path also:
Example:
By default, the node finds the index.js file in that folder and loads it. Otherwise, we can also create a package.json file in that folder where we can define the node module name which we want to load by default.
Import in Node.js
As required works in the CommonJs modules system, similarly, import is used for including modules in ES6 (version 6 of the ECMA Script) module system. Which means import is used to include an ES module. At present Node.js doesn’t support ES6 import directly. So if we try to use the import keyword for importing modules directly in node js it will throw out the error. So how can we use import for including modules then you can do so in the following ways:
Using ".mjs" extension
The first way to use the ES6 import statement in Node.js is to save the JavaScript file with the ".mjs" extension, instead of using the typical ".js" extension.
As mentioned above the default module system for Node.js is CommonJs which supports require function for importing modules. So if we want to use the ECMAScript module system then the ".mjs" extension helps us achieve that.
Using package.json file
By this method, we can use the ".js" extension while using the import statement of ECMAScript. For this, we need to include a package.json file in our project. And the content of package.json should be like this:
The "type" property present in the above package.json file helps in deciding the module system that the project should use. The "type" can be "module" or "commonjs". If the type is "module" then it enables the ECMAScript module system, whereas if the type is "commonjs" then it is of the CommonJS module system.
We can use import statements in the following ways:
Become a coding wizard with our Free Node JS course. Join now and master the art of server-side programming.
Difference between Require and Import
require | import |
---|---|
It is used in the CommonJS module system. | It is used in the ES6 (ECMAScript version 6) module system. |
Loading is synchronous in require (i.e., modules are imported sequentially.) | Loading is asynchronous in import (i.e., modules are imported without waiting for previous module import to complete.) |
Because of synchronous loading performance of require less efficient than import. | Because the Asynchronous loading performance of import is better than required. |
If we import a module using require then the complete module is imported. So, memory usage is more. | Using import we can selectively load pieces of code in the module. So, memory usage is less compared to require. |
require imports of the components exported by module. exports in the module. | import includes components exported by export in the module. |
require can be called directly as it is the default way of importing. | To use import in our project we need to enable ES6 or ECMAScript module in our project. |
require can be called anywhere in the program | import works only at the top of the program |
Conclusion
- Modules are encapsulated blocks of code that are used in the external application based on its related functionality.
- Modules can be included in the project using two ways: require or import.
- require is a built-in function to import modules provided by the CommonJS module system.
- import statements are used in ES6 or ECMAScript module system to include modules.
- require includes the complete file whereas by import we can include specific export components only.
- To use The ES6 module system in the project, follow any of these two steps:
- Use the ".mjs" extension in place of the default ".js" extension in the project.
- Edit the value of the "type" property in the package.json file to "module".
Looking for More Than Just JavaScript? Our Full Stack Developer Course Explores Advanced Front and Back-End Techniques. Enroll Now!