Can't export function expression: "TypeError: xxx is not a function"

Can't export function expression: "TypeError: xxx is not a function"

我试图遵循模块的基本指南。我创建了 test_module.js

var textFunction = function() {
    console.log("text");
};

exports = textFunction;

然后我尝试在我的 app.js:

中使用它
var textFunction = ('./test_module');

textFunction();

但是我得到一个错误:

 TypeError: textFunction is not a function

我是不是做错了什么?或者这是一个非常古老的指南?

PS:导出只有在我这样声明时才有效:

exports.text = function() {
    console.log("text");
}

exports 是局部变量。分配给它不会改变导出的值。你想直接赋值给module.exports

module.exports = textFunction;

module.exportsexports 最初引用相同的值(一个对象),但分配给 exports 不会改变 module.exports,这才是重要的。 exports 存在是为了方便。


另一个问题是您没有正确要求该模块,但这可能只是一个错字。你应该做

var textFunction = require('./test_module');

var textFunction = ('./test_module'); 只是将字符串 './test_module' 赋值给 textFunction 我们都知道字符串不是函数。