Alex Ilyin
Alex Ilyin

Reputation: 1304

How to use node module in client code?

I've installed ReactJs module in my nodejs application, so React appeared in node_modules directory. But I can't use it in client javascript because there is no reference.

So what is the best way to add such a reference ? (Of course I can manually copy react.js script to scripts folder and add reference manually but it leads to code duplication and looks ugly)

Upvotes: 3

Views: 1607

Answers (1)

Nicky McCurdy
Nicky McCurdy

Reputation: 19554

Browserify is the tool you are looking for. It takes Node modules and wraps them so you can require() them in client side JavaScript code.

Example from Browserify's readme

Whip up a file, main.js with some require()s in it. You can use relative paths like './foo.js' and '../lib/bar.js' or module paths like 'gamma' that will search node_modules/ using node's module lookup algorithm.

var foo = require('./foo.js');
var bar = require('../lib/bar.js');
var gamma = require('gamma');

var elem = document.getElementById('result');
var x = foo(100) + bar('baz');
elem.textContent = gamma(x);

Export functionality by assigning onto module.exports or exports:

module.exports = function (n) { return n * 111 }

Now just use the browserify command to build a bundle starting at main.js:

$ browserify main.js > bundle.js

All of the modules that main.js needs are included in the bundle.js from a recursive walk of the require() graph using required.

To use this bundle, just toss a <script src="bundle.js"></script> into your html!

Upvotes: 4

Related Questions