Write JavaScript modules that works both in NodeJS and Browser (with requirejs)

Last week I was trying to write a simple JavaScript module that will parse a Markdown links from a given markdown strings and output them as an array. So, I want to challenge myself a bit and try to make sure that my one single library file will work not only in NodeJS app, but will also work in browser. Now in browser it could be done multiple ways and there are really two way of writing this module that I care the most. One is writing it to work in requirejs environment and the other with very basic <script> tag include in the HTML file.

The challenge was if I have to write in node module's way it will not work in requirejs as exports is not something that will work in requirejs and if I have to use define sure it won't work in nodejs as well.

This is how you write for node only (COMMONJS)...

function foo() {  
// do something

module.exports = foo;  

The above will work in other environment if you will add some extra code to check if module exist in browser and if not you will do something else to make sure it won't break, but I prefer not simply I like to make sure the code is clean and find a way that will work for sure.

And, this is how you do in browser...

function foo() {  
// do something

window.foo = foo;  

Obviously there are many ways to write simple module in browser, but this is one of the example here.

Also, for requirejs uses AMD...

define(['jquery'] , function ($) {  
    return function () {};

Now to make sure we understand onething that to make your module works in all environments you will have to use only things that will work for sure for example you can't use require() that avaiable in nodejs environment with browser as that is not part of the browser (if you include some extra library it will work I guess).

So, how to make it work in all environments?


(function(global) {
  foo = function () {
    //do something

  global.foo = foo;


The above code will work in nodejs, browser and requirejs. I prefer to do it this way as I don't have to include any extra library in node or add any conditions to make sure I don't have something that might break the library.

There are many ways to write a code that will work in requirejs and node, but you will have to add library like amd-loader which will then convert your amd module and make it work with nodejs, but again that will require you to add extra library.

If you have a better way or suggestion please leave a comment down below :)