I was using both require
and import
but got some different behaviors from both. Until now I was assuming that require
and import
are just ES5 vs ES6. I was doing the below:
abc.js
console.log("abc");
xyz.js
console.log("xyz");
hello.js
require("./abc");
import "./xyz";
and the second time when I changed the file and swapped the two lines.
hello.js
import "./xyz";
require("./abc");
Both the times it was giving the same output
xyz
abc
ie. output of require
was always after the import. If I use only import, or only import
, it was giving consoles as expected ie. one after the other.
Can anyone help in understanding this?
Modules declared in
hello.js
viaimport
are imported before any code inhello.js
is run. It doesn't matter if theimport
statement appears after another statement. The module is still loaded before the code is run. So that is why you are getting "xyz" first no matter where you put theimport
statement.require()
on the other hand is programmatic. The module code is run when therequire()
statement is encountered while your program is running.