简体   繁体   中英

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.

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);
}();

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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