Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use node module in client code?

Tags:

node.js

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)

like image 962
Alex Ilyin Avatar asked Jul 21 '26 14:07

Alex Ilyin


1 Answers

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!

like image 73
Nick McCurdy Avatar answered Jul 24 '26 06:07

Nick McCurdy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!