node.js和浏览器javascript中的常用模块

时间:2022-09-04 09:57:34

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目录中使用相同的文件?

3 个解决方案

#1


45  

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

这似乎是如何使模块成为可以在客户端使用的东西。

http://caolanmcmahon.com/posts/writing_for_node_and_the_browser

http://caolanmcmahon.com/posts/writing_for_node_and_the_browser

mymodule.js:

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');

#2


19  

node.js和浏览器javascript中的常用模块

Browserify

Browserify

It magically lets you do that.

它神奇地让你这样做。

#3


2  

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

Webmake用于将CommonJS / NodeJS模块移植到浏览器。试一试

#1


45  

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

这似乎是如何使模块成为可以在客户端使用的东西。

http://caolanmcmahon.com/posts/writing_for_node_and_the_browser

http://caolanmcmahon.com/posts/writing_for_node_and_the_browser

mymodule.js:

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');

#2


19  

node.js和浏览器javascript中的常用模块

Browserify

Browserify

It magically lets you do that.

它神奇地让你这样做。

#3


2  

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

Webmake用于将CommonJS / NodeJS模块移植到浏览器。试一试