【问题标题】:Accessing config variables from other config files从其他配置文件访问配置变量
【发布时间】:2014-10-26 16:37:58
【问题描述】:

我在一个配置文件中使用另一个配置文件中设置的配置变量时遇到问题。例如

// file - config/local.js
module.exports = {
  mongo_db : {
    username : 'TheUsername',
    password : 'ThePassword',
    database : 'TheDatabase'
  }
}

// file - config/connections.js
module.exports.connections = {
  mongo_db: {
    adapter: 'sails-mongo',
    host: 'localhost',
    port: 27017,
    user: sails.config.mongo_db.username,
    password: sails.config.mongo_db.password,
    database: sails.config.mongo_db.database
  },
}

当我“升帆”时,我收到以下错误:

user: sails.config.mongo_db.username,
      ^
ReferenceError: sails is not defined

我可以在其他地方访问配置变量 - 例如,这可行:

// file - config/bootstrap.js
module.exports.bootstrap = function(cb) {
  console.log('Dumping config: ', sails.config);
  cb();
}

这会将所有配置设置转储到控制台 - 我什至可以在其中看到 mongo_db 的配置设置!

我很困惑。

【问题讨论】:

    标签: sails.js


    【解决方案1】:

    您无法访问配置文件中的sails,因为在处理这些文件时仍在加载 Sails 配置!在 bootstrap.js 中,您可以访问 bootstrap 函数中的配置,因为该函数在 Sails 加载后被调用,而不是 above功能。

    在任何情况下,config/local.js 都会合并到所有其他配置文件之上,因此您可以通过这种方式获得所需的内容:

    // file - config/local.js
    module.exports = {
      connections: {
        mongo_db : {
          username : 'TheUsername',
          password : 'ThePassword',
          database : 'TheDatabase'
        }
      }
    }
    
    // file - config/connections.js
    module.exports.connections = {
      mongo_db: {
        adapter: 'sails-mongo',
        host: 'localhost',
        port: 27017
      },
    }
    

    如果你真的需要从另一个访问一个配置文件,你总是可以使用require,但不建议这样做。由于 Sails 基于多个因素(包括当前环境)将配置文件合并在一起,因此您可能会读取一些无效选项。最好按预期方式做事:使用 config/env/* 文件进行环境特定设置(例如 config/env/production.js)、config/ local.js 用于特定于单个系统(例如您的计算机)的设置,其余文件用于共享设置。

    【讨论】:

    • 酷 - 这很有意义。我想我被@mikermcneil 对这个问题的评论吓跑了:stackoverflow.com/questions/18267706(请参阅最后一条评论,他似乎确认您可以访问其他配置文件中的配置变量)谢谢 - 我会尝试使用配置组合/env 和 config/local。
    • 是的,我不确定他是否真的打算回答之前的评论!
    • 我见过的最糟糕的框架。如果你打算在 config/http 中做任何值得注意的事情,比如访问 redis,就会导致需要复制代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    相关资源
    最近更新 更多