gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:30:53 36 4
gpt4 key购买 nike

现在,我使用 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');

关于javascript - 对 CommonJS 配置文件使用全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29222877/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com