What is the best way to use JavaScript modules on Server and Browser?
I'm currently building an JavaScript project that uses NodeJS and some objects are shared between client and server side. I was trying to use the module system on node but I couldn't find a suitable implementation of the node modules on the brow开发者_如何学Pythonser. Currently my test architecture is like this:
Framework.js (just creating a common namespace and some functions that the whole framework should know. It is on folder named Shared)
var Framework = {};
exports.Framework = Framework;
Module.js (Part of the framework responsible for a specific part)
var fw = require('../Shared/Module.js');
fw.Module = function() {};
exports.Framework = fw;
These modules go on and on. I tried using a simple common.js implementation found on the web but it had some bugs on the scope created by the module. I also tried the idea shown on this post http://caolanmcmahon.com/posts/writing_for_node_and_the_browser although it doesn't work, since I have to require the base object in my modules which wouldn't work on the browser.
How should I structure this code in a way that I can organize my code having different modules on different files to use (some of them) in server and browser?
There are JavaScript module libraries that both work on browsers and Node. One example: RequireJS:
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node.
精彩评论