简体   繁体   English

node.js 和浏览器 javascript 中的公共模块

[英]Common module in node.js and browser javascript

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.我正在开发一个 node.js 应用程序,我想在客户端使用我为 node.js 服务器创建的模块。

An example module would be circle.js:一个示例模块是 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?我怎么能在我的客户端 javascript 的 web 目录中使用相同的文件?

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 https://caolan.org/posts/writing_for_node_and_the_browser.html

mymodule.js:我的模块.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');

浏览器化

Browserify浏览器化

It magically lets you do that.它神奇地让你做到这一点。

Webmake was made to port CommonJS/NodeJS modules to browser. Webmake用于将 CommonJS/NodeJS 模块移植到浏览器。 Give it a try试试看

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM