简体   繁体   English

需要模块时,squareArea不是函数

[英]squareArea is not a function when requiring module

I made a set of functions and none of them is working. 我做了一组功能,但没有一个起作用。 Here's one of them, for example: 例如,这是其中之一:

function squareArea(side) {
  var sArea = side * side;
  return sArea;
}

And this is how I require the module: 这就是我require模块的方式:

var mfs = require("m-p-formulas-js");
var test = mfs.squareArea(2);
console.log(test)

It returns this error: 它返回此错误:

TypeError: mfs.squareArea is not a function

What should I do to solve this? 我该怎么做才能解决这个问题?

You aren't exporting the function so it doesn't exist on the require d module object. 您没有导出函数,因此在require d模块对象上不存在该函数。 Assuming you're using ES5, use module.exports which contains the module's exports: 假设您使用的是ES5,请使用module.exports ,其中包含模块的导出:

function squareArea(side) {
  var sArea = side * side;
  return sArea;
}
module.exports = {
  squareArea: squareArea
};

You could also shorten it to this using the exports shortcut: 您还可以使用exports快捷方式将其缩短为:

exports.squareArea = squareArea;

You need to export the function to make it available to others. 您需要导出功能以使其对其他人可用。 Add the following to the bottom of your definition of mp-formulas-js module: 将以下内容添加到mp-formulas-js模块的定义的底部:

module.exports = {
    squareArea
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM