【问题标题】:Express.JS not recognizing required js file's functionsExpress.JS 无法识别所需 js 文件的功能
【发布时间】:2012-08-10 19:29:10
【问题描述】:

尽管我已经导入了包含我将使用的函数的 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

你知道出了什么问题吗? game_core 包含函数:

var game_core = function(game_instance){....};

【问题讨论】:

    标签: javascript express


    【解决方案1】:

    添加到game_core.js的末尾:

    module.exports = {  
        game_core : game_core  
    }  
    

    到games.js:

    var game_core = require('./game_core').game_core(game_istance);
    

    【讨论】:

      【解决方案2】:

      在 Node 中要求模块不会将其内容添加到全局范围。每个模块都包装在自己的范围内,因此您必须 export public names:

      // game_core.js
      module.exports = function (game_instance){...};
      

      然后在主脚本中保留对导出对象的引用:

      var game_core = require('./game_core.js');
      ...
      thegame.gamecore = new game_core( thegame );
      

      您可以在文档中了解更多信息:http://nodejs.org/api/modules.html#modules_modules

      【讨论】:

        【解决方案3】:

        另一种方法:

        if( 'undefined' != typeof global ) {
            module.exports = global.game_core = game_core;
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-01-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-01-22
          • 2019-08-01
          • 2011-10-01
          相关资源
          最近更新 更多