2

我正在尝试根据环境自定义公共 javascript 文件。具体来说,对于 socket.io,我正在尝试自定义客户端将连接到的位置:

发展:

var socket = io.connect('http://localhost/chat');

生产:

var socket = io.connect('http://xxx.xxx.xxx.xxx/chat');

我了解应用程序本身内的所有环境变量(并且我确实通过 express 使用节点环境变量),但据我所知,这些变量不会触及我为客户端提供的公共静态 js 文件。

根据开发/生产环境实现这种上下文切换的最佳方法是什么?

4

2 回答 2

1

If you're writing unobtrusive JavaScript and using a proper bundling system, then each HTML page you deliver should reference only a single "loader" script, which is then responsible for bringing in all the rest of the scripts. Create two versions of that script, one for development and one for production, and give them different names. When rendering HTML, make the name of the script a template variable which you'll have set based on your environment. Your loader script can then set appropriate variables to be used by the scripts it brings in.

于 2012-08-01T05:39:58.270 回答
0

我接近它的方法是在布局页面中加载 socket.io:

<script src='<%= socketIoUrl %>/socket.io/socket.io.js'></script>

<script type="text/javascript">
    var socket = io.connect('<%= socketIoUrl %>');
</script>

然后我添加了一个动态助手来公开socketIoUrl

var helpers = function(app) {

    app.dynamicHelpers({
        socketIoUrl: function(req, res) {
            return app.settings.socketIoUrl;
       }
    });
};

module.exports = helpers;

所以在我的 server.js 文件中,我根据环境设置了适当的值并加载了帮助文件:

app.configure('development', function(){
    app.set('socketIoUrl', 'http://localhost:3003');
});

app.configure('test', function(){
    app.set('socketIoUrl', 'http://...');
});

app.configure('production', function(){
    app.set('socketIoUrl', 'http://...');
});

require('./apps/helpers')(app);

因此,现在您可以socket在您拥有的任何其他 js 文件中使用在布局页面中创建的变量。

于 2012-08-01T07:29:28.153 回答