Node.js-为每个目录导出index.js中的所有文件是一种好做法吗? //configs/index.js module.exports={ AppConfig:require(“./app config”), AuthConfig:require('./auth-config'), DbConfig:require('./数据库配置'), }; //控制器/some-controller.js const{AppConfig}=require('../configs'); //测试/some-test.spec.js //它失败是因为控制器需要()根index.js,并且隐式运行所有导出的文件。 const SomeController=require('../controllers/some controller');
上面的示例在开发中运行良好,但在使用Node.js-为每个目录导出index.js中的所有文件是一种好做法吗? //configs/index.js module.exports={ AppConfig:require(“./app config”), AuthConfig:require('./auth-config'), DbConfig:require('./数据库配置'), }; //控制器/some-controller.js const{AppConfig}=require('../configs'); //测试/some-test.spec.js //它失败是因为控制器需要()根index.js,并且隐式运行所有导出的文件。 const SomeController=require('../controllers/some controller');,node.js,Node.js,上面的示例在开发中运行良好,但在使用mocha进行单元测试时失败,因为它隐式运行所有导出的文件。我的解决方法是像下面这样直接导入文件require('../configs/app config')您首选的解决方案是什么?我应该导出所有文件吗?这是一种好的做法吗?您可以创建一个ConfigService-类来封装对配置文件的访问,而不是导出/导入每个“子配置”。比如: const lodash = require('lodash'); export class ConfigService {
mocha
进行单元测试时失败,因为它隐式运行所有导出的文件。我的解决方法是像下面这样直接导入文件require('../configs/app config')
您首选的解决方案是什么?我应该导出所有文件吗?这是一种好的做法吗?您可以创建一个ConfigService
-类来封装对配置文件的访问,而不是导出/导入每个“子配置”。比如:
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'),
}
}
}
class DbController {
constructor() {
this.dbHost = ConfigService.get('DbConfig').dbHost;
// ...
}
}