【问题标题】:Using globals for CommonJS config files为 CommonJS 配置文件使用全局变量
【发布时间】:2015-03-24 00:25:45
【问题描述】:

现在我正在使用 CommonJS 模块在我的脚本中设置一些全局变量,而不是在每个脚本中手动设置它们。

index.spec.js

/*globals browser, by, element*/
require('./config.js')();

describe('exampleApp', function() {
    'use strict';

    beforeEach(function() {
        browser.get('http://localhost:8080/');
    });

    describe('index view', function() {
        it('should have a title', function() {
            expect(browser.getTitle()).to.eventually.equal('Example App');
        });
    });
});

config.js

/*globals global*/
module.exports = function() {
    'use strict';

    global.chai = require('chai');
    global.promised = require('chai-as-promised');
    global.expect = global.chai.expect;

    global.chai.use(global.promised);
}();

但是,在这里使用全局对象似乎是一种不好的做法。有没有更好的办法?也许一种方法可以将本地范围内的变量加载到我 require-ing 到的文件中?

【问题讨论】:

    标签: javascript module npm commonjs


    【解决方案1】:

    您可以只导出一个配置对象并在所有需要该配置对象的文件中使用它吗?

    'use strict';
    
    var config = {};
    config.chai = require('chai');
    config.promised = require('chai-as-promised');
    config.expect = config.chai.expect;
    config.chai.use(config.promised);
    
    module.exports = config;
    

    然后在所有使用配置的文件中都需要这个:

    var config = require('config.js');

    【讨论】:

    • 我想这是最好的选择。可悲的是expect 被频繁使用,我需要覆盖全局而不是仅仅使用config.expect。不过,感谢您的建议。
    猜你喜欢
    • 2016-06-22
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    相关资源
    最近更新 更多