30

I am developing a node.js app, and I want to use a module I am creating for the node.js server also on the client side.

An example module would be circle.js:

var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

and you do a simple

var circle = require('./circle')

to use it in node.

How could I use that same file in the web directory for my client side javascript?

mal-wan
  • 4,391
  • 4
  • 26
  • 37
RobKohr
  • 6,611
  • 7
  • 48
  • 69
  • Possible duplicate of [How can I share code between Node.js and the browser?](https://stackoverflow.com/questions/3225251/how-can-i-share-code-between-node-js-and-the-browser) – tevemadar Apr 09 '19 at 10:16

3 Answers3

47

This seems to be how to make a module something you can use on the client side.

https://caolan.org/posts/writing_for_node_and_the_browser.html

mymodule.js:

(function(exports){

    // your code goes here

   exports.test = function(){
        return 'hello world'
    };

})(typeof exports === 'undefined'? this['mymodule']={}: exports);

And then to use the module on the client:

<script src="mymodule.js"></script>
<script>
    alert(mymodule.test());
</script>

This code would work in node:

var mymodule = require('./mymodule');
AppDeveloper
  • 1,816
  • 7
  • 24
  • 49
RobKohr
  • 6,611
  • 7
  • 48
  • 69
19

Browserify

Browserify

It magically lets you do that.

generalhenry
  • 17,227
  • 4
  • 48
  • 63
2

Webmake was made to port CommonJS/NodeJS modules to browser. Give it a try

Mariusz Nowak
  • 32,050
  • 5
  • 35
  • 37