为什么这个NPM包说它不是构造函数?

时间:2017-05-06 01:58:12

标签: node.js npm

我正在开发一个需要我使用this NPM package的Sails.js项目。我创建了一个新的Sails.js服务来在npm install之后调用这个包 - 就像这样:

// Require and initialize the rules engine
var jsonRulesEngine = require('json-rules-engine'),
    rulesEngine = new jsonRulesEngine();

当我运行此脚本时,出现以下错误:

/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/async.js:61
        fn = function () { throw arg; };
                           ^

TypeError: jsonRulesEngine is not a constructor
    at Object.verify (/Users/Nag/Code/learn-nodejs/server/api/services/RulesService.js:21:27)
    at Object.wrapper [as verify] (/Users/Nag/Code/learn-nodejs/server/node_modules/@sailshq/lodash/lib/index.js:3250:19)
    at /Users/Nag/Code/learn-nodejs/server/api/controllers/UtilsController.js:113:43
    at /Users/Nag/Code/learn-nodejs/server/api/services/RedisService.js:55:13
    at tryCatcher (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/util.js:16:23)
    at Promise.successAdapter [as _fulfillmentHandler0] (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/nodeify.js:23:30)
    at Promise._settlePromise (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/promise.js:566:21)
    at Promise._settlePromise0 (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/promise.js:693:18)
    at Async._drainQueue (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues (/Users/Nag/Code/learn-nodejs/server/node_modules/bluebird/js/release/async.js:17:14)
    at Immediate.<anonymous> (/Users/Nag/Code/learn-nodejs/server/node_modules/async-listener/glue.js:188:31)
    at runCallback (timers.js:666:20)
    at tryOnImmediate (timers.js:639:5)
    at processImmediate [as _immediateCallback] (timers.js:611:5)
[nodemon] app crashed - waiting for file changes before starting...

为什么我可能会收到错误?在包的示例部分中,包的所有者使用ES6格式导入包,而我需要它。这有什么不同吗?

1 个答案:

答案 0 :(得分:3)

当您需要NPM软件包时,根据您的模块系统 1 ,执行此操作时将不会自动导入默认导出

var jsonRulesEngine = require('json-rules-engine');

因此,当您需要时,它将返回模块对象,而不是按预期返回默认。在json-rules-package包中,Engine 默认导出,但您的要求不需要默认值。如果您记录返回的模块对象,它将如下所示:

{
  Engine: function(...) { ... },
  Fact: function(...) { ... },
  Operator: function(...) { ... },
  Rule: function(...) { ... },
  default: function(...) { ... }
}

引擎位于default Engine 属性下。你可以这样做:

var jsonRulesEngine = require('json-rules-engine').default();

或者:

var jsonRulesEngine = require('json-rules-engine').Engine;

第一个将明确导入默认导出。然后你可以像这样创建一个类的实例:

var rulesEngine = new jsonRulesEngine();

1 是的,使用ES2015 import会影响结果。如果您使用ES2015中的import语法,则不会遇到此问题。要知道为什么看this answer。简而言之,Babel转换ES2015代码,以便在需要导入默认导出时显式访问default