在客户端JavaScript,如何可以改变我的variables基于环境?

好的,所以我使用node.js,它很棒。

我一直在本地工作,直到最近,我有点沮丧,我改变我的代码,每次只是部署。

具体来说,我使用套接字io,我需要告诉套接字它住在哪里:

var _socket = io.connect('http://localhost:5000'); 

当我在本地去的时候,这很好,但是每次我部署到我的testing服务器时,我都需要改变这个…这很烦人。 在其他语言中,我可以通过configuration文件来做到这一点。

在节点,在服务器端,我可以设置variables基于我的环境就像这样…

 app.configure('development', function(){ process.env.PORT = 5000; }); 

我可以在客户端做类似的事吗?

您必须以某种方式将此variablesembedded到客户端HTML代码中(即在Jade模板中)。

如果您显示服务器端代码提供HTML,我可能能够确定它可能在哪里。

我通常做这样的事情:

 (function(){ var config = { host: 'localhost', port: '8080', setEnv: function(env){ switch (env){ case 'development': this.host = 'devserver'; this.port = '80'; break; case 'production': this.host = 'prodserver'; this.port = '80'; break; } } }; console.log(config.host); console.log(config.port); config.setEnv('production'); console.log(config.host); console.log(config.port); })(); 

如果你用grunt构build你的应用程序,那么使用grunt-variablize 。 把你的configuration放到resources/config.json

 { "test": { "socketUrl": "http://localhost:5000" }, "prod": { "socketUrl": "http://your-production.com:5000" } } 

configurationvariables任务:

 grunt.initConfig({ /* ... */ variablize: { target: { input: "resources/config.json", output: "dist/config.js", variable: "Config", property: grunt.option('profile') } } }); 

运行grunt --profile=testgrunt --profile=prod并以这种方式使用它:

 var _socket = io.connect(Config.socketUrl); 

这取决于你如何在节点端进行pipe理。 就像如果你有不同的configuration文件的每个环境。 例如。 production.js,development.js等。然后你可以在该configuration中定义url或设置一个env。 设置这个基地url或环境。 进入服务器端的HTML模板并渲染。 在客户端,您可以轻松阅读env。 或基地url。 在我的情况下,我有一套基于环境的url。 我在configuration文件中定义了环境,在客户端创build了一个configuration文件。 所以基于env。 configuration文件可以设置URL。

  angular.module('core').constant('config',{ 'apiUrl' :{ 'beta': 'http://api-beta.xyzdev.com', 'dev': 'http://api-dev.xyzdev.com', 'production': 'http://api-prod.xyzdev.com' } }); 

在客户端,这应该足够了:

 var _socket = io.connect(); 

socket.io将自动检测主机和端口。

编辑

如果url匹配地址和端口,你也可以这样做:

 var _socket = io.connect(document.location.protocol+'//'+document.location.host);