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?

1

3 Answers 3

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');
Sign up to request clarification or add additional context in comments.

Comments

19

Browserify

Browserify

It magically lets you do that.

2 Comments

Not sure how that actually is used to do what I was looking for. It seems to solve some other problem.
And browserify keeps getting better and better.
2

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

Comments

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.