噶:找不到variables:出口

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

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

现在我的业力testing使用PhantomJs并抱怨不存在的exportsvariables

 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中的exportsvariables?

通常的模式通常是检查是否定义了exportsvariables:

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

这个模式在Backbone中用作例子 – 从源代码来看,它在技术上有点复杂,因为它也支持AMD,但是它的想法就是这样。

您也可以按下传递它作为包装函数的第一个参数的检查:

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

看看这个博客文章了解更多信息。