Using Node.js modules in HTML

Erel Segal-Halevi picture Erel Segal-Halevi · Jan 27, 2014 · Viewed 12.9k times · Source

I have the following Node.js project (which is a Minimal Working Example of my problem):

module1.js:

module.exports = function() {
    return "this is module1!";
};

module2.js:

var module1 = require('./module1');
module.exports = function() {
    return module1()+" and this is module2!";
};

server.js:

var module2 = require('./module2');
console.log(module2());  // prints: "this is module1! and this is module2!"

Now I want to create a client.html file that will also use module2.js. Here is what I tried (and failed):

naive version:

<script src='module2.js'></script>
<script>alert(module2());</script> // should alert: "this is module1! and this is module2!"

This obviously doesn't work - it produces two errors:

  • ReferenceError: require is not defined.
  • ReferenceError: module2 is not defined.

Using Node-Browserify: After running:

browserify module2.js > module2.browserified.js

I changed client.html to:

<script src='require.js'></script>
<script>
    var module2 = require('module2');
    alert(module2());
</script>

This doesn't work - it produces one error:

  • ReferenceError: module2 is not defined.

Using Smoothie.js by @Torben :

<script src='require.js'></script>
<script>
    var module2 = require('module2');
    alert(module2());
</script>

This doesn't work - it produces three errors:

  • syntax error on module2.js line 1.
  • SmoothieError: unable to load module2 (0 )
  • TypeError: module2 is not a function

I looked at require.js but it looks too complicated to combine with Node.js - I didn't find a simple example that just takes an existing Node.js module and loads it into a web page (like in the example).

I looked at head.js and lab.js but found no mention of Node.js's require.

So, what should I do in order to use my existing Node.js module, module2.js, from an HTML page?

Answer

Mariusz Nowak picture Mariusz Nowak · Jan 27, 2014

The problem is that you're using CJS modules, but still try to play old way with inline scripts. That won't work, it's either this or that.

To take full advantage of CJS style, organize your client-side code exactly same way as you would for server-side, so:

Create client.js:

var module2 = require('./module2');
console.log(module2());  // prints: "this is module1! and this is module2!"

Create bundle with Browserify (or other CJS bundler of your choice):

browserify client.js > client.bundle.js

Include generated bundle in HTML:

<script src="client.bundle.js"></script>

After page is loaded you should see "this is module1! and this is module2!" in browser console