Differences Between Require and Import
Modules are a key construct to know JavaScript. We’ll cover JavaScript modules: require and import during this Require vs Import article. These modules permit you to put in writing reusable code. By using Node Package Manager (NPM), you’ll publish your module to the community. Also, NPM permits you to utilize modules created by alternative developers.
There is 2 module system you’ll select in JavaScript:
Importing modules using require and commercialism using a module. Exports and exports. Importing modules using ES6 import and commercialism using ES6 export. Are there any performance edges to using one over the other? Is there the rest that we must always recognize if we tend to use ES6 modules over Node ones? Let’s attempt to solve this problem.
What is Require?
Require are accustomed to consuming modules. It permits you to incorporate modules into your programs. You’ll embrace intrinsically core Node.js modules, community-based modules (node modules) and native modules.
Let’s say we would like to scan a file from the file system. The node contains a core module referred to as ‘fs’:
const fs = require('fs');
fs.readFile('./file.txt', 'utf-8', (err, data) => {
if(err) { throw err; }
console.log('data: ', data);
});
As you’ll see, we have a tendency to import the “fs” module into our program. It allows us to any function attached to it, like “readFile”.
Require can look around for files within the following order:
Built-in core Node.js modules (like fs)
Modules in the node_modules folder.
If the module name contains a ./, / or ../, it’ll look around for the directory within the given path. It matches the extensions: *.js, *.json and *.node.
Require Features:
- You will have dynamic loading wherever the loaded module name is not predefined /static or wherever you do not absolutely load a module, providing it’s “truly required” (depending on bound code flow).
- Loading is synchronous. Meaning if you have got multiple requires, they’re loaded and processed one by one.
- You will have dynamic loading wherever the loaded module name is not predefined /static or wherever you do not absolutely load a module, providing it’s “truly required” (depending on bound code flow).
- Loading is synchronous. Meaning if you have got multiple requires, they’re loaded and processed one by one.
- The requirement is not customarily based mostly. It’s is extremely unlikely to become customary currently that ES6 modules exist.
The actual loading of any module using require() happens in five steps.
- Resolution
- Loading
- Wrapping
- Evaluation
- Caching
The first step resolution is an enclosed step wherever node.js calculates the file methods etc., within the second that is loading; the node pulls the code within the current method. In wrapping in wraps up the code within the operate as shown higher than so sends it to VM for evaluating, eventually catching it.
So, the node is never aware of what symbols a commonJS module goes to export until and unless the module is truly evaluated. And this is often the largest distinction with ECMAScript modules, as a result of ESM is lexical, and so, the exported symbols are better-known before the code is truly evaluated.
What is Import?
There is a proposal of import() operate too to form nested import statements. In contrast to the lexical import keyword, import() operate is processed at the time of analysis (more like require). The syntax is just like the following.
import(“foo”).then((module) => ).catch((err)=>);
When the associate ESM module is parsed, then before the VM evaluates it, an enclosed structure referred to as a Module Record is made. As a result, any error concerning the inconvenience of a couple of any exported image can raise a blunder before the analysis.
Use Cases
- The on-demand module load is feasible.
- The conditional load of modules is doable.
- A promise like asynchronous handling.
Import features:
- You will use named imports to by selection load solely the items you would like. Which will save memory?
- Import is asynchronous (and in the current ES6 Module Loader, it, of course, is) and may perform a touch higher.
- You will use named imports to by selection load solely the items you would like. Which will save memory?
- Import is asynchronous (and in the current ES6 Module Loader, it, of course, is) and may perform a touch higher.
- Imports don’t seem to be obtainable in Node because of version 6.
- However, it’d are available in future versions. You’ll use it these days, using transpilers similar to Traceur Compiler, Babel or Rollup.
Head to Head Comparison Between Require and Import (Infographics)
Below are the top 4 differences between Require vs Import
Key Differences Between Require and Import
Both are popular choices in the market; let us discuss some of the major differences:
- Require is more of dynamic analysis, and import is more of static analysis.
- Require Throws error at runtime and Import throws error while parsing
- Require is Nonlexical and Import is Lexical
- Requires to stay where they have put the file, and imports get sorted to the top of the file.
- Import is always run at the very beginning of the file and can’t be run conditionally. On the other hand, require can be used inline, conditionally,
Require vs Import Comparison Table
As you can see, there are many comparisons. Let’s look at the top comparison are below:
S. No. | Require | Import |
1 | Syntax:
var dep = require(“dep”); console.log(dep.bar); dep.foo(); |
Syntax:
import {foo, bar} from “dep”; console.log(bar); foo(); |
2 | As import remains in stage three and not enforced by browsers natively, we’re unable to run any performance take a look at. | Presently once you use import in your code, your transpilers it back to require the commonJS modeling system. Therefore for nowadays, each is the same. |
3 | Though there aren’t any performance profit at the instant, however, I’ll still counsel to use import over require because it’s about to be native in JS and will (just as a result of its native) perform higher than require. | As a result of import is native; therefore, require doesn’t perform higher as compare to import |
4 | You will have dynamic loading wherever the loaded module name is not predefined. Loading is synchronous. Meaning if you have got multiple requires, they’re loaded and processed one by one. ES6 | You can use named imports to by selection load solely the items you would like. Which will save memory? Import is asynchronous (and in the current ES6 Module Loader, it, of course, is) and may perform a touch higher. Also, the require module system is not customarily based mostly. It’s is extremely unlikely to become customary currently that ES6 modules exist. |
Conclusion
We learned concerning a way to produce Node.js modules and use them in our code. Modules permit us to utilize code simply. They supply practicality that’s isolated from alternative modules. Code is less complicated to manage once it’s in little, bite-sized chunks. This is often the thinking behind keeping functions to just one task or having files contain solely some, or one, part at a time. If you have got a fancy app and ought to scroll through lots of or thousands of lines of code, then the task of debugging or simply understanding the app becomes that abundant tougher. Luckily JavaScript helps us out with this by having. However, you’ll write code in one file and share that code, therefore. Stay tuned to our blog for more articles like these.
Recommended Article
This has been a guide to the top differences between Require vs Import. Here we also discuss the key differences with infographics and comparison tables. You may also have a look at the following articles to learn more –
- Node.js vs PHP Performance
- Raspberry Pi 3 vs Arduino
- C# Array vs List
- C++ vs Objective C
- C++ vs Visual C++: Which is the best
600+ Online Courses | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6
View Course
Related Courses