【问题标题】:Karma: Can't find variable: exports业力:找不到变量:出口
【发布时间】:2014-10-04 19:12:32
【问题描述】:

我写了一个可以同时用于后端和客户端的节点模块

(exports || window).Bar= (function () {
    return function () { .... }
})();

现在我的业力测试使用 PhantomJs 并抱怨不存在的 exports 变量

gulp.task('test', function () {
    var karma = require('karma').server;

    karma.start({
        autoWatch: false,
        browsers: [
            'PhantomJS'
        ],
        coverageReporter: {
            type: 'lcovonly'
        },
        frameworks: [
            'jasmine'
        ],
        files: [
            'bar.js',
            'tests/bar.spec.js'
        ],
        junitReporter: {
            outputFile: 'target/junit.xml'
        },
        preprocessors: {
            'app/js/!(lib)/**/*.js': 'coverage'
        },
        reporters: [
            'progress',
            'junit',
            'coverage'
        ],
        singleRun: true
    });
});

我得到的错误是

PhantomJS 1.9.7 (Mac OS X) ERROR
   ReferenceError: Can't find variable: exports

有没有办法忽略 karam/phantomsJs 中的 exports 变量?

【问题讨论】:

    标签: javascript node.js phantomjs karma-runner node-modules


    【解决方案1】:

    一个常见的模式通常是检查exports变量是否被定义:

    (function(){
      ...
      var Bar;
      if (typeof exports !== 'undefined') {
        Bar = exports;
      } else {
        Bar = window.Bar = {};
      }
    })();
    

    此模式以in Backbone 为例 - 好吧,它在源代码中的技术有点复杂,因为它也支持 AMD,但想法就是这样。

    您还可以将检查下推,将其作为包装函数的第一个参数传递:

    (function(exports){
    
      // your code goes here
    
      exports.Bar = function(){
          ...
      };
    
    })(typeof exports === 'undefined'? this['mymodule']={}: exports);
    

    查看at this blog post 了解更多信息。

    【讨论】:

    猜你喜欢
    • 2017-11-24
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 1970-01-01
    • 2017-03-01
    • 2015-12-27
    • 2017-02-12
    相关资源
    最近更新 更多