JS 中的 Importing(require) 模块是否也执行整个代码?

问题描述

modulefile.js 为

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

console.log(`hello from module`);

exports.calcModule = calc;

并让 main.js 与 modulefile.js 位于同一目录

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

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

当我在控制台中将 main.js 作为 $ node main.js 执行时
结果就像

hello from module
3

我很难理解 hello from module 也打印出来了。
导入模块是否包括执行整个模块文件

解决方法

是的。第一次使用 require() 加载 CommonJS 模块时,会执行任何顶级代码。如您所见,情况必须如此,exports.calcModule = calc 才能运行并为模块建立导出,而您的 console.log('hellow from module') 也会运行。

一旦加载,模块就会被缓存,因此对同一模块的任何其他对 require() 的调用只会返回模块最初执行时的导出对象,并且顶层代码不会再次运行。因此,无论该模块在您的程序中加载了多少次,顶级代码都只会运行一次。

导入一个模块是否包括执行整个模块文件?

是的,它会执行您正在加载的模块中的所有顶级代码。