简体   繁体   English

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

[英]Karma: Can't find variable: exports

I've written a node module which can be used for both the backend and client 我写了一个节点模块,可以用于后端和客户端

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

Now my karma tests use PhantomJs and complain about the not existing exports variable 现在我的业力测试使用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
    });
});

The error I get is 我得到的错误是

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

Is there a way to ignore the exports variable in karam/phantomsJs ? 有没有办法忽略karam / phantomsJs中的exports变量?

A common pattern is usually to check whether the exports variable is defined: 常见的模式通常是检查是否定义了exports变量:

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

This pattern is used in Backbone as example - well, it's technically bit more complicated in the source code because it does support also AMD, but the idea it's this. 这种模式在Backbone中用作示例 - 嗯,它在源代码中技术上有点复杂,因为它确实支持AMD,但这就是它的想法。

You can also push down the check passing it as first argument of the wrapping function: 你也可以按下检查传递它作为包装函数的第一个参数:

(function(exports){

  // your code goes here

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

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

Have a look at this blog post for more info. 有关详细信息,请查看此博客文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM