如何导入导出模块将值返回到其他js文件
试图掌握导出导入/导出过程并将函数和它们返回到另一个文件。我遇到了这个很好的例子!但无法将其转移到另一个文件中..
例如,运行node testing.js时出现此错误。我认为你可以通过你的参数。
错误输出
console.log(testClass.authy)(app);
^
ReferenceError: app is not defined
helper.js
module.exports.auth = function (app) {
console.log("return authy")
var app = "1";
return app;
};
testing.js
const testClass = require('../commands/helper.js');
console.log(testClass.auth)(app);
回答如下:
首先,在将函数的结果记录到控制台时,您应该使用console.log(function())
,而不是console.log(function)()
。
其次,你将'app
'作为参数传递,这是你赋予函数的值,然后立即重新定义它。你的函数不需要任何参数,它应该只是function() { ... }
,然后被称为testClass.auth()
。现在,您正在尝试将变量'app
'传递给您尚未定义的函数。
所以最后,你的代码应该是:
helper.js
module.exports.auth = function () {
console.log("return authy")
var app = "1";
return app;
};
testing.js
const testClass = require('../commands/helper.js');
console.log(testClass.auth());
'app
'的值返回到console.log
函数,然后显示它。希望这可以帮助!