在 node.js 中,模块中的一个文件如何查看模块中另一个文件中的函数

in node.js, how does one file in a module see functions in another file in the module?

本文关键字:模块 文件 一个 何查看 函数 另一个 js node      更新时间:2023-09-26

在包含两个文件的模块中 ./modxmodx.jshelper.js

./

modx/package.json:

{ "name" : "module x",
  "main" : "./modx.js" }

./modx/helper.js:

function subFunc() { }
./modx

/modx.js:

exports.mainFunc = function() {
   var x = subFunc();
}

helper.js中的subFunc()都在modx模块中时,如何使modx.js看到?

Inside ./modx/helper.js

var subFunc = function subFunc() {}
exports.subFunc = subFunc;

在 .modx/modx 里面.js

var helper = require('./helper.js');
exports.mainFunc() {
    var x = helper.subFunc();
}

这里的结果是 helper.js 中的 subFunc 函数在外部可用,而 modx.js 中的 mainFunc 在外部可用。

脚本中唯一A从脚本B可见的对象是module.exports。将对象/函数添加到module.exports(就像您使用mainFunc所做的那样)使它们从外部可见。没有其他办法。