为什么我不能从单独的 .js 文件中调用任何函数?

Why can't I call any functions from a separate .js file?

如果我有以下 main.js 文件:

require('./test.js');

$(document).ready(function(){
    testFunction();
});

然后是与 main.js:

相同目录中的对应 test.js 文件
function testFunction()
{
    console.log('from test.js');
}

我收到错误:

Uncaught TypeError: testFunction is not a function

如果我尝试将 require 语句设置为变量 x,然后在我的主 js 文件中调用 x.testFunction,那么我会得到相同的错误,但会出现 x.testFunction

我如何让它工作?我需要能够从单独的 js 文件中调用函数。

您需要从具有以下功能的文件中导出:

function fooBar() {
    console.log('hi');
}

module.exports = fooBar;

然后,您可以在其他文件中使用它,例如:

var foo = require('./fooBar');
foo();

如果你想从另一个文件中导出多个函数,你也可以使用一个对象:

module.exports = {
    fooBar: fooBar, 
    Baz: Baz
};

并使用它:

foo.fooBar();
foo.Baz();

还有许多其他选项和可能性,请务必阅读文档。