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

标签 javascript module npm commonjs

现在,我使用 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/

相关文章:

node.js - 在上传到 S3 存储桶之前将给定图像调整为 3 种不同的尺寸

angular - 无法完成 ionic 电容器添加android命令

javascript - 创建为 var 的函数没有 .name 属性。为什么?

javascript - 嵌套调用的 MongoDB 回调返回问题

javascript - 检查输入文本是否已填充并显示不同的div

linux - 针对模块的内核 Makefile 链接

Python:ModuleNotFoundError:没有名为 'xyz' 的模块

javascript - 不需要的图标出现在 IE8 中的图像上

python - 从同级目录导入 Python 类

node.js - 退出状态 3 npm-lifecycle\index.js :285:16