Surya Purohit
Surya Purohit

Reputation: 1120

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

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?

Upvotes: 1

Views: 124

Answers (2)

code-jaff
code-jaff

Reputation: 9330

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

Upvotes: 1

Trott
Trott

Reputation: 70075

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.

Upvotes: 2

Related Questions