Common module in node.js and browser javascript

后端 未结 3 1507
离开以前
离开以前 2020-12-29 03:09

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:

<
相关标签:
3条回答
  • 2020-12-29 03:44

    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');
    
    0 讨论(0)
  • 2020-12-29 03:49

    Browserify

    Browserify

    It magically lets you do that.

    0 讨论(0)
  • 2020-12-29 03:49

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

    0 讨论(0)
提交回复
热议问题