Explore the features of the methods require() and import() in JavaScript
Both require() and import() are used to includes modules. But they have several important features you should be aware of. But before we dwell on that, let's go over each of them a bit in detail.
require() In Node.js, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object. require() statement not only allows to add built-in core NodeJs modules but also community-based and local modules
var myVar = require('http'); //to use built-in modules
var myVar2 = require('./myLocaModule'); //to use local modules
import() The import() & export() statement are used to refer to an ES module. Other modules with file types such as .json cannot be imported with these statements. They are permitted to be used only in ES modules and the specifier of this statement can either be a URL-style relative path or a package name. Also, the import statement cannot be used in embedded scripts unless such script has a type = 'module'. A dynamic import can be used for scripts whose type is not 'module'.
var myVac = import("module-name");
require() vs import()
1.require() can be called from anywhere Usually, we call the import() or require() statements at the beginning of a file. But you can call require() from anywhere in the code while import() statements can only be defined at the beginning of the file. Defining a import() statement elsewhere will give you an error or automatically shift to the file's beginning.
2.require() can be called conditionally require() statements can be called conditionally but import() statements can not be. Refer to the code given below:
//require
if(user.id == 1){
const getBlogTitle = require(‘./blogDetails.js’);
}
//import
if(...) {
import ...; // Error, not allowed!
}
{
import ...; // Error, we can't put import in any block
}
3. ES modules can be called dynamically Now that said, there is a way to call imports dynamically which is different from conditional but can help with asynchronous loading issues
//dynamic import
let {hi, bye} = await import('./say.js');
hi(); // Hello!
bye(); // Bye!
//OR
let say = await import('./say.js');
say.hi(); // Hello!
say.bye(); // Bye!
4. import() statements are asynchronous require() statements are called synchronous one by one whereas import() called asynchronously and they are known to perform well compared to require() functions in large-scale applications.