how to use node.js module system on the clientside


Question

I would like to use the CommonJS module system in a clientside javascript application. I chose nodejs as implementation but can't find any tutorial or docs on how to use nodejs clientside, ie without using node application.js

I included node.js like this in my html page:

<script type="text/javascript" src="node.js"></script>

Note that I didn't make nodejs on my local machine, I'm on Windows anyway (I'm aware of the Cygwin option). When I want to use the require function in my own javascript it says it's undefined.

var logger = require('./logger');

My question is, is it possible to use nodejs like this?

1
34
2/9/2011 12:32:51 PM

Accepted Answer

Node.js is a serverside application where you run javascript on the server. What you want to do is use the require function on the client.

Your best bet is to just write the require method yourself or use any of the other implementations that use a different syntax like requireJS.

Having done a bit of extra research it seems that no-one has written a require module using the commonJS syntax for the client. I will end up writing my own in the near future, I recommend you do the same.

[Edit]

One important side effect is that the require function is synchronous and thus loading large blocks of javascript will block the browser completely. This is almost always an unwanted side-effect. You need to know what you're doing if you're going to do this. The requireJS syntax is set up so that it can be done asynchronously.

15
1/4/2013 4:39:12 PM

SubStack on github has a module called node-browserify.

It will compress and bundle your modules and deliver it as a single js file, but you use it just like Node.js (example from module readme):

<html>
    <head>
    <script type="text/javascript" src="/browserify.js"></script>
    <script type="text/javascript">
        var foo = require('./foo');

        window.onload = function () {
            document.getElementById('result').innerHTML = foo(100);
        };
    </script>
</head>
<body>
    foo = <span style='font-family: monospace' id="result"></span>
</body>
</html>

From the module description:

Browserify

Browser-side require() for your node modules and npm packages**

Browserify bundles everything ahead-of-time at the mount point you specify. None of this ajaxy module loading business.

More features:

  • recursively bundle dependencies of npm modules
  • uses es5-shim for browsers that suck
  • filters for {min,ugl}ification
  • coffee script works too!

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon