问题描述
因此,当我使用此require('fileName.js')将外部JavaScript文件添加到主index.js文件中时。
在index.js中
const caltor = require('./calculate.js');
console.log(caltor.adding(5,7));
在我的calculate.js中
function adding (i,y){
return i+y;
}
顺便说一句,我正在使用nodejs执行。
console.log(caltor.adding(5,7));
^
TypeError: caltor.adding is not a function
解决方法
您需要将函数“ adding”导出到“ calculate.js”文件中。
module.exports = adding;
在index.js文件中,无需调用caltor.adding()(假设您仅从“ calculate.js”导出一个函数)。
console.log(caltor(5,7));
,
Node.js模块不会自动导出其顶级作用域变量/函数。
要导出值,您有两种方法:
-
将其添加到
exports
对象节点模块具有预定义的变量
exports
,其值将被导出。向其中添加功能:function adding (i,y){ return i+y; } exports.adding = adding
const caltor = require('./calculate.js'); console.log(caltor.adding(5,7));
您还可以通过这种方式导出多个值,只需确保为它们指定一个不同的名称即可。
function adding (i,y){ return i+y; } exports.adding = adding function subtracting (i,y){ return i-y; } exports.subtracting = subtracting
const caltor = require('./calculate.js'); console.log(caltor.adding(5,7)); console.log(caltor.subtracting(5,7));
-
通过分配给
提供“默认”导出module.exports
如果要导出单个值,可以将其分配给
module.exports
。在这种情况下,它变为require
返回的值。请注意,在分配
module.exports
之后,在exports
变量上定义属性将不再起作用。都不会将任何分配给exports
的变量导出任何内容。function adding (i,y){ return i+y; } module.exports = adding
const adding = require('./calculate.js'); console.log(adding(5,7));