Developing for node and the browser
Here’s one method of writing JavaScript in node that also runs in the browser. It requires the browser version of the project to be built and involves some string manipulation during the build process – but it does not require you to include any additional logic in your code, which is always a plus. Basically this technique boils down to how you structure your node.js files, structuring your files as such:
var App = {};
App.ObjectOne = (function() {
var ObjectOne = function() {};
// ...
module.exports = ProjectOne;
})();
With the above file structure we can use a simple find and replace on module.exports to create the following output.
App.ObjectOne = (function() {
var ObjectOne = function() {};
// ...
return ObjectOne;
})();
Notice that we had to declare App in the node.js file but then stripped it out again during the build process. The node.js file needs this because each file/module has it’s own scope, so App needs to be declared in each module.
Anyway, if you perform the find and replace on all files in your project, and then merge those together – or merge then find and replace, you end up with something like this:
App.ObjectOne = (function() {
var ObjectOne = function() {};
// ...
return ObjectOne;
})();
...
App.ObjectTen = (function() {
var ObjectTen = function() {};
// ...
return ObjectTen;
})();
If you prepend a line of code to declare App again then you will have a single, merged, js file containing all of your project code that should also run in the browser.
To summarise, here are the steps again:
- Copy all the files.
- Merge them together.
- Perform find and replace on each node.js file
- Declare App
I have a working example of this implemented with Grunt for the build process. Here’s a link to the gruntfile for anyone interested:
https://github.com/KarlPurk/jsmapper/blob/master/Gruntfile.js