How to write modules that are both nodejs compatible and browser compatible?

I am writing a node module {collection of modules}and in future this might be ported to browser environments too. For that reason I am looking for programming techniques that will allow me to write code once and then reuse the same, may be if it requires some kind of running build , its fine.

Its fine if this is the workflow,

  • write node modules
  • run some build script that converts above written code into a single js file to be able to run in browser enviroments

Please do not suggest me browserify.

Why no browserfiy or any other similar stuff? I saw the code that was generated . It was huge and had lot of browserify introduced code. I found it difficult to troubleshoot and go through the code i have written

I really recommend giving another look at Browserify. Other than that, add a Universal Module Definition (UMDJS) exporter in your files. This will allow you to expose your modules in node, browserify, requirejs/amd, or just thrown into a script tag on any site.

Can also use a module transpiler -- write in a ES6 module exporter, and have it convert for use in a browser, or a commonjs/node environment.

Well, Darren, let's consider I have some Agent object which would require XMLHttpRequest for its transport layer browser-side but use NodeJS' http API server-side.

Where do you make the switch using Grunt for example? Let's say we've got the following files: Agent.js, transport-browser.js and transport-node.js. Maybe I'm off on your technique but it is something like I would go for (I'm currently thinking about all that).