gpt4 book ai didi

node.js - 无法导出函数表达式 : "TypeError: xxx is not a function"

转载 作者:搜寻专家 更新时间:2023-11-01 00:41:19 25 4
gpt4 key购买 nike

我试图遵循模块的基本指南。我创建了 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:export 只有在我这样声明时才有效:

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 我们都知道字符串不是函数。

关于node.js - 无法导出函数表达式 : "TypeError: xxx is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33533409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com