简体   繁体   English

对CommonJS配置文件使用全局变量

[英]Using globals for CommonJS config files

Right now I'm using a CommonJS module to set some global variables in my scripts rather than setting them manually in each script. 现在,我正在使用CommonJS模块在脚本中设置一些全局变量,而不是在每个脚本中手动设置它们。

index.spec.js 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 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);
}();

However, using the global object here seems like bad practice. 但是,在此处使用全局对象似乎是不好的做法。 Is there a better way? 有没有更好的办法? Maybe a way to load variables scoped locally scoped to the file I'm require -ing into? 也许是一种加载变量的方法,该变量的作用域是我require本地文件?

You could just export a config object and require it in all the files that need the configuration object? 您可以只导出配置对象,并在需要该配置对象的所有文件中都需要它吗?

'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;

And then just require this in all the files that use the configuration: 然后,在使用该配置的所有文件中都需要这样做:

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

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

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