[英]Express.JS not recognizing required js file's functions
Even though, I've imported the JS file that includes the function that I will use, Node.JS says that it is undefined. 即使我导入了包含将要使用的功能的JS文件,Node.JS仍未定义。
require('./game_core.js');
Users/dasdasd/Developer/optionalassignment/games.js:28
thegame.gamecore = new game_core( thegame );
^
ReferenceError: game_core is not defined
Do you have any idea what's wrong? 你知道怎么了吗 Game_core includes the function:
Game_core包含以下功能:
var game_core = function(game_instance){....};
Add to the end of game_core.js: 添加到game_core.js的末尾:
module.exports = {
game_core : game_core
}
to games.js: 到games.js:
var game_core = require('./game_core').game_core(game_istance);
Requiring a module in Node doesn't add its contents to the global scope. 在Node中要求模块不会将其内容添加到全局范围中。 Every module is wrapped in its own scope, so you have to export public names :
每个模块都包装在自己的作用域中,因此您必须导出公共名称 :
// game_core.js
module.exports = function (game_instance){...};
Then keep a reference in your main script to the exported object: 然后在您的主脚本中保留对导出对象的引用:
var game_core = require('./game_core.js');
...
thegame.gamecore = new game_core( thegame );
You can read more about it in the docs: http://nodejs.org/api/modules.html#modules_modules 您可以在文档中阅读有关此内容的更多信息: http : //nodejs.org/api/modules.html#modules_modules
An alternative approach: 替代方法:
if( 'undefined' != typeof global ) {
module.exports = global.game_core = game_core;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.