What is the difference between require() and import
Problem:
I am working on a node js project. I installed all the npm packages using npm. For importing node_module packages there are two ways to do it require and import. If they do the same work then what are the difference.
In this article, we are going to learn what is the difference between "require()" and "import"
Solution:
When you use require it automatically scans node_modules to find modules. But when you use import it does not. The major difference is in require, the entire js file is called no matter if you do not need some part of it.
const exampleObj = require("./exampleFile.js")
Here the entire exampleFile is called to get the exampleObj.
import { exampleObj } from './exampleFile.js';
But using import only exampleFile will import not the full code. Require is an old method of importing data where import is an ES6 feature. Also, I should mention, that you can use require anywhere in your program but you always have to call import at the top of the file.