我们正在构建一个使用一组 REST API 的主干应用程序。理想情况下,我们想要为 dev 和 live 提供不同的配置文件,这些配置文件由环境变量决定。可能吗。
提前致谢
我们正在构建一个使用一组 REST API 的主干应用程序。理想情况下,我们想要为 dev 和 live 提供不同的配置文件,这些配置文件由环境变量决定。可能吗。
提前致谢
I recommend you to have one file in a way like this:
var YourProject = {};
YourProject.Config = {
Local : {
db : 'mysql:dumy:dummy@localhost',
relativeUrl : 'blabla',
otherConfig : '123456'
},
Dev : {
db : 'mysql:dumy:dummy@localhost',
relativeUrl : 'blabla',
otherConfig : '123456'
},
Production : {
db : 'mysql:dumy:dummy@localhost',
relativeUrl : 'blabla',
otherConfig : '123456'
}
}
And then in your utilities to have something like this:
YourProject.ConfigHandler = {
getValue : function(key){
var env;
switch( window.location.hostname ){
case "localhost":
case "127.0.0.1":
env = 'Local';
break;
case "dev.yourdomain.com":
env = 'Dev';
break;
case "yourdomain.com":
env = 'Production';
break;
default:
throw('Unknown environment: ' + window.location.hostname );
}
return YourProject.Config[env][key];
}
};
So you will have just one file and for call differents API DB urls you will need to call just one line:
YourProject.ConfigHandler.getValue( 'db' );
您的问题可以针对任何 javascript 应用程序,而不仅仅是骨干应用程序,因此以下答案更笼统:
我要做的是有一个 config.js 文件,它是您的 HTML 中加载的第一件事。内容只是一个带有配置的 JSON 对象:
var CONFIG = {
debug : false,
server : 'http://production.foo.com'
};
现在您的应用程序的每个组件都可以访问配置,因为 CONFIG 是一个全局对象。所以你可以在你的应用程序的任何地方写这个:
if (CONFIG.debug) {
console.log('my debug stuff...');
}
诀窍是拥有 2 个 config.js 文件。一种用于开发,一种用于生产。当您想要发布您的应用程序时,捆绑您的生产 config.js 文件并将其上传到您的服务器。
您可以创建一个构建脚本来构建您的生产应用程序。作为第一步,它可以将正确的 config.js 文件复制到正确的位置。您还可以添加步骤来缩小 js 文件,将它们捆绑到一个文件中等等。
我改编了丹尼尔对 Coffeescript/CommonJS 的好回答,所以config.coffee
我有:
env = switch window.location.hostname
when "localhost", "127.0.0.1"
"development"
when "www.example.com", "example.com"
"production"
config =
development:
urlRoot: "http://localhost:3000"
production:
urlRoot: "http://www.example.com"
module.exports = config[env]
然后客户端代码如下所示:
config = require("config")
config.urlRoot