Shareable Code for Node and Browser
I had a simple problem along the way of exploring Node.js, which involves writing modules that work for both server and client sides. Just like many programmers nowadays, I google’d out a solution (which was written by the person who authored async
, so I guess I need to thank him at least twice).
However this doesn’t solve all my problem since I am way too lazy to get rid of all those amazing open source libraries. And:
Of course, the browser doesn’t support many other node features like require(), so you’ll need to test that your code is suitable for use in the browser first.
– Caolan McMahon
Realizing dependencies can be passed into the exposed module as its arguments, I have finally landed a solution that is simple (for me) to grasp.
Say I needed to have a shared utility module for both Node.js and browser to use, one that rely on underscore.js and moment.js, which fortunately have fairly consistent interfaces for both platforms.
1 | // my module that relies on underscore.js and moment.js |
So now I could use this sweet little module in node:
1 | // expose public directory to client side |
and in browser:
1 | <script src="js/underscore.min.js"></script> |
For now, I am satisfied.