首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Node.js -为每个目录导出index.js中的所有文件是一个很好的实践吗?

Node.js -为每个目录导出index.js中的所有文件是一个很好的实践吗?
EN

Stack Overflow用户
提问于 2020-06-17 12:07:09
回答 1查看 53关注 0票数 0
代码语言:javascript
复制
// configs/index.js
module.exports = {
  AppConfig: require('./app-config'),
  AuthConfig: require('./auth-config'),
  DbConfig: require('./database-config'),
};

// controllers/some-controller.js
const { AppConfig } = require('../configs');

// tests/some-test.spec.js
// it fails because the controller require() the root index.js and it runs all exported files implicitly.
const SomeController = require('../controllers/some-controller');

上面的示例在开发中运行良好,但是它在使用mocha的单元测试中失败,因为它隐式地运行所有导出的文件。我的解决办法是像这个require('../configs/app-config')那样直接导入文件。您最喜欢的解决方案是什么?我应该导出所有文件吗?这是一个很好的练习吗?

EN

回答 1

Stack Overflow用户

发布于 2020-06-17 12:20:51

您可以创建一个ConfigService-class来封装对配置文件的访问,而不是导出/导入每个“子信任”。类似于:

代码语言:javascript
复制
const lodash = require('lodash');

export class ConfigService {

    static configuration = ConfigService.initConfig();

    static get(key) {
        return _.get(ConfigService.configuration, key);
    }
    // you can remove this if you don't want to support adding/changing configs at runtime
    static add(key, val) {
        if (ConfigService.configuration[key]) {
            throw new Error(`Could not add a new configuration key <${key}>. This key exists already!`);
        }
        _.set(ConfigService.configuration, key, val);
    }

    static initConfig() {
        ConfigService.configuration = {
            AppConfig: require('./app-config'),
            AuthConfig: require('./auth-config'),
            DbConfig: require('./database-config'),
        }
    }

}

使用非常简单,它甚至允许您在单元测试中模拟配置值(通过阻塞get-method):

代码语言:javascript
复制
class DbController {

    constructor() {
        this.dbHost = ConfigService.get('DbConfig').dbHost;
        // ...
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62428663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档