Reputation: 1304
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
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.
Whip up a file,
main.js
with somerequire()
s in it. You can use relative paths like'./foo.js'
and'../lib/bar.js'
or module paths like'gamma'
that will searchnode_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
orexports
:module.exports = function (n) { return n * 111 }
Now just use the
browserify
command to build a bundle starting atmain.js
:$ browserify main.js > bundle.js
All of the modules that
main.js
needs are included in thebundle.js
from a recursive walk of therequire()
graph using required.To use this bundle, just toss a
<script src="bundle.js"></script>
into your html!
Upvotes: 4