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)
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.jswith 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.exportsorexports:module.exports = function (n) { return n * 111 }Now just use the
browserifycommand to build a bundle starting atmain.js:$ browserify main.js > bundle.jsAll of the modules that
main.jsneeds are included in thebundle.jsfrom a recursive walk of therequire()graph using required.To use this bundle, just toss a
<script src="bundle.js"></script>into your html!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With