2014-10-04 78 views
5

我已經寫了可用於後端和客戶端噶:找不到變量:出口

(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 

有沒有忽略出口瓦里的方式能在卡拉姆/ phantomsJs?

回答

6

一個常見的模式通常是檢查exports變量是否被定義:

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

這種圖案用於爲例 - 好,它在技術上位在源代碼中更復雜,因爲它支持也AMD ,但它的想法是這樣的。

您也可以倒推把它當作包裝功能部件的第一個參數的檢查:

(function(exports){ 

    // your code goes here 

    exports.Bar = function(){ 
     ... 
    }; 

})(typeof exports === 'undefined'? this['mymodule']={}: exports); 

有更多信息看at this blog post

+2

但實際上OP代碼的問題是什麼? – 2014-10-05 19:57:27

+1

看看這個SO回答:http://stackoverflow.com/questions/4725603/variable-undefined-vs-typeof-variable-undefined – MarcoL 2014-10-05 20:45:58