Reputation: 13781
I have a NodeJS application with common constants between the client and the server.
The constants are stored in variables rather than inline. Those variables could be defined in two separate files, one for client and one for server.
File 1:
// client_constants.js
MESSAGE_TYPE_A = "a";
MESSAGE_TYPE_B = "b";
File 2:
// server_constants.js
exports.MESSAGE_TYPE_A = "a";
exports.MESSAGE_TYPE_B = "b";
To avoid duplicate code I would like to store constants in a single location and a single format for both the client and the server. Wat do?
Upvotes: 2
Views: 1181
Reputation: 2624
Sort of like Hector's answer, but works in my version of Node and in my browser because it uses comparisons to "undefined"
and typeof
.
var context = (typeof exports != "undefined") ? exports : window;
context.constant_name = "constant_name_string";
Upvotes: 1
Reputation: 26690
You can do something like this:
// constants.js
root = exports ? window
root.MESSAGE_TYPE_A = "a";
root.MESSAGE_TYPE_B = "b";
"exports" does not exist on the client side in which case it will use the default "window" object.
Upvotes: 4