Require and import showing different behaviors. Why is this so?

107 views Asked by At

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?

2

There are 2 answers

0
Trott On

Modules declared in hello.js via import are imported before any code in hello.js is run. It doesn't matter if the import 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 the import statement.

require() on the other hand is programmatic. The module code is run when the require() statement is encountered while your program is running.

0
code-jaff On

Since ES6 modules yet to be implemented(not sure) in node.js, I'm assuming you're using babel for transpiling export, import statements.

When babel transpiling the code it always place the import statements at the top of the module, therefore this happens. You can test it in REPL.

DEMO

More in depth details on import and require