co_lin
co_lin

Reputation: 135

Does Importing(require) module in JS also executes whole code as well?

let moduleFile.js as

const calc = {
    add(a,b) = {return a+b},
    sub(a,b) = {return a-b}
}

console.log(`hello from module`);

exports.calcModule = calc;

and let main.js which is in same dir with moduleFile.js as

const { calcModule } = require(`./moduleFile`);

console.log(calcModule.add(1,2));

when i execute main.js as $ node main.js in console
result would be like

hello from module
3

its hard for me to understand that hello from module also printed.
does importing a module includes executing whole module file?

Upvotes: 2

Views: 1717

Answers (1)

jfriend00
jfriend00

Reputation: 708136

Yes. The first time a CommonJS module is loaded with require(), any top level code is executed. As you can see, this has to be the case so that exports.calcModule = calc runs and establishes the exports for the module and your console.log('hellow from module') would also run.

Once loaded, the module is cached so any other calls to require() for that same module will just return the export object from the original execution of the module and the top level code will not run again. So, the top level code only runs once, no matter how many times the module is loaded within your program.

does importing a module includes executing whole module file?

Yes, it executes all top level code in the module you are loading.

Upvotes: 6

Related Questions