샘플 라이브러리가 기본 라이브러리와 추가 모듈로 나뉘어져 있다고 가정 해 보겠습니다. 기본 모듈은 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; };
(메인 모듈 + 서브 모듈), 아마 그들이 구성하고 있지만 많이 나아 졌어.
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>
: 나는 기본 index.html
파일을 준비했습니다. 이제는 node.js (브라우저 지원을 중단하지 않음)에 대한 지원을 제공하려고합니다. 즉시 invoked-fun-expr에 정의를 런타임 중에 계산되는 루트 매개 변수로 묶었습니다 (노드의 경우 module.exports
). 그렇지 않으면 this==window
(브라우저)입니다. 코드는 다음과 같습니다 : I 노드를 실행하면
(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] } }
을하지만 서브 모듈을 수입하기 위해 무엇을 할 수 있는가?
[UMD interesting] (https://github.com/umdjs/umd)을 찾을 수 있습니다. – Andy
@Andy 링크에 감사드립니다. 어쨌든, 나는 그것을 사용하는 방법에 대한 조언이 필요하다고 생각합니다. 내가 필요한 것은'nodeAdapter.js' (결국 node.js와 requireJS 지원이 필요하다)라고 생각한다. – ducin