node.js和浏览器javascript中的常用模块 [英] Common module in node.js and browser javascript

查看:86
本文介绍了node.js和浏览器javascript中的常用模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个node.js应用程序,我想在客户端使用我为node.js服务器创建的模块。

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.

示例模块是circle.js:

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;
};

你做了一个简单的

var circle = require('./circle')

使用在节点中。

如何在我的客户端javascript的web目录中使用相同的文件?

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

推荐答案

这似乎就是如何制作一个可以在客户端使用的模块。

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

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>

此代码适用于节点:

var mymodule = require('./mymodule');

这篇关于node.js和浏览器javascript中的常用模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆