业力:无法找到变量:出口

Jea*_*eri 5 javascript node.js phantomjs node-modules karma-runner

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

(exports || window).Bar= (function () {
    return function () { .... }
})();
Run Code Online (Sandbox Code Playgroud)

现在我的业力测试使用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
    });
});
Run Code Online (Sandbox Code Playgroud)

我得到的错误是

PhantomJS 1.9.7 (Mac OS X) ERROR
   ReferenceError: Can't find variable: exports
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*coL 6

通常的模式通常是检查exports变量是否已定义:

(function(){
  ...
  var Bar;
  if (typeof exports !== 'undefined') {
    Bar = exports;
  } else {
    Bar = window.Bar = {};
  }
})();
Run Code Online (Sandbox Code Playgroud)

这种模式在Backbone中用作示例 - 嗯,它在源代码中技术上有点复杂,因为它确实支持AMD,但这就是它的想法.

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

(function(exports){

  // your code goes here

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

})(typeof exports === 'undefined'? this['mymodule']={}: exports);
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请查看此博客文章.

  • 但OP的代码实际上是什么问题? (2认同)