2014-07-18 52 views
0

可以说'我有一个样本库拆分为2个文件:基础库和附加模块。基本模块驻留在module.js如何为(子)模块提供node.js和浏览器支持

var Calculator = { 
    add: function(a, b) { return a + b; }, 
    sub: function(a, b) { return a - b; } 
}; 

附加模块位于submodule.js

if (typeof Calculator == "undefined") {                                                           
     var Calculator = {};                                                             
}                                                                    

Calculator.mul = function(a, b) { return a * b; };                                                        

Calculator.div = function(a, b) { return a/b; }; 

这是库有多少JS内置(主模块+子模块),虽然可能他们配置好多了。我已经准备了一个基本的index.html文件:

Calculator.add(3,4) 
7 
Calculator.sub(3,4) 
-1 
Calculator.mul(3,4) 
12 
Calculator.div(3,4) 
0.75 

这是所有的库做什么:

<html> 
<head> 
     <script type="text/javascript" src="module.js"></script> 
     <script type="text/javascript" src="submodule.js"></script> 
</head> 
<body> 
</body> 
</html> 
加载磁带库和使我能够执行它的浏览器(以下控制台输出)内

。现在我想提供对node.js的支持(不支持浏览器)。我已经用立即调用的fun-expr中的定义包含了一个根参数,该参数在运行时计算得出:节点的module.exports(如果存在)或this==window(浏览器)。代码如下所示:

(function(root) { 

     root.Calculator = { 
       add: function(a, b) { return a + b; }, 
       sub: function(a, b) { return a - b; } 
     }; 

}(typeof module == 'undefined' ? this : module.exports)); 

当我运行节点,我可以导入模块:

> var c = require('./module.js') 
undefined 
> c 
{ Calculator: { add: [Function], sub: [Function] } } 

,但我能做些什么来导入子模块?

+1

你可能会发现[UMD有趣](https://github.com/umdjs/umd)。 – Andy

+0

@安迪感谢您的链接,情况就是如此。无论如何,我想我仍然需要一些关于如何使用它的建议。我想我需要的是'nodeAdapter.js'(最后我需要node.js和requireJS支持) – ducin

回答

0

socket.io也许是很好的例子。你可以从那里看到结构。