我正在将代码库从 100% 浏览器端切换为浏览器端和服务器端的混合。
我发现的问题是,要让我的代码使用 node.js 运行,我必须使用模块。为了将我的代码变成模块,需要对几乎所有代码进行巨大的重构。原因是在浏览器上,许多功能是跨文件使用的,而不用担心任何命名空间。
但目前,在 Node.js 中,我发现没有办法达到同样的效果,而且我找到的所有解决方案都不起作用。
举个我想要的例子,我希望能够做到这一点:
////////////
// file1.js
////////////
function someFunction(someArgs) {
/* run some stuff, calculate some stuff */
return something;
}
////////////
// file2.js
////////////
function someFunction2(someArgs) {
/* run some code */
let someValue = someFunction(someArgs);
/* run some more code */
}
////////////
// file3.js
////////////
someFunction2(myArguments);
I have tried following solutions found
here https://stackoverflow.com/questions/5797852/in-node-js-how-do-i-include-functions-from-my-other-files, but they have not helped me.
“马赛卢姆”的答案不符合我的需要。
"Udo G"的答案,指使用 eval 将其他文件包含在运行文件中会引发此错误:
console.log(isWhitelisted("test"));
^
ReferenceError: isWhitelisted is not defined
at Object.<anonymous> (/Users/< snip >/server.js:45:13)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:139:18)
at node.js:999:3
尽管 Udo G 指出了这一点,因为我正在使用严格模式:
另请注意,这不适用于“use strict”;
“尼克·帕诺夫”的答案对我来说也不起作用,抛出了与 Udo G 的答案相同的错误。这也可能是因为使用严格。
有什么方法可以在不重构整个代码库以坚持使用模块的情况下实现这一目标?