3

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)

1 Answer 1

4

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!

Sign up to request clarification or add additional context in comments.

3 Comments

Wow, thanks for such a detailed answer. Do I have to call browserify every time I need client side script update ?
I mean If i change client side javascript. My guess was that bundle.js contains both client side and server side code so I have to recreate it when client side code changes
As far as I'm aware, you should only need to run a Browserify command when you update a something in node_modules, not when your other client side code is updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.