Reputation: 726
I'm trying to customize public javascript files based upon the environment. Specifically, for socket.io, I'm trying to customize the location the client will connect to:
development:
var socket = io.connect('http://localhost/chat');
production:
var socket = io.connect('http://xxx.xxx.xxx.xxx/chat');
I know all about environment variables within the app itself (and I do use node environment variables through express), but from what I can tell these variables won't touch the public static js files I'm serving to the client.
What's the best way to go about achieving this contextual switch based upon development/production environments?
Upvotes: 3
Views: 343
Reputation: 3986
The way I approached it was to load the socket.io in the layout page:
<script src='<%= socketIoUrl %>/socket.io/socket.io.js'></script>
<script type="text/javascript">
var socket = io.connect('<%= socketIoUrl %>');
</script>
Then I added a dynamic helper to expose the socketIoUrl
:
var helpers = function(app) {
app.dynamicHelpers({
socketIoUrl: function(req, res) {
return app.settings.socketIoUrl;
}
});
};
module.exports = helpers;
And so in my server.js file I set the appropriate value based on the environment and loaded the helper file:
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);
So now you can use the socket
variable created in your layout page in any other js file you have.
Upvotes: 0
Reputation: 15003
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.
Upvotes: 1