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

Using globals for CommonJS config files

本文关键字:全局变量 配置文件 CommonJS      更新时间:2023-09-26

现在我使用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中的文件?

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

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