exports.add = function(a,b) { return a + b; };
This article provides tutorial on how to make JavaScript code, written in CommonJS module format, work with RequireJS in GateIn.
Below is an example of two CommonJS modules and JavaScript code in template of my_portlet portlet that uses the two modules.
exports.add = function(a,b) { return a + b; };
var add = require('math').add; exports.increment = function(val) { return add(val,1); };
<div> <script type="text/javascript"> //Business code using math.js and increment.js var increment = require('increment').increment; alert(increment(100));//Expect to see 101 in alert message </script> </div>
GateIn automatically wraps JavaScript code bundled under an ON_LOAD resource in one module definition block, that makes sense as underlying JavaScript code does not have AMD format but turns to break things as the code is already in AMD format. Native script feature helps us in case there is is need to escape JavaScript resource from automatic wrapping.
define("foo",["d1", "d2"], function(d1, d2) { .... });
<module> <name>foo</name> <native-script>path_to_foo.js</native-script> </module>
The steps to make JavaScript code in CommonJS module format work in GateIn are:
Wrap each CommonJS module in one AMD module definition block
Declare each converted CommonJS module as native-script resource
Wrap business code using CommonJS modules in callbacks passed to one require block of RequireJS
We wrap each CommonJS module with a block
define([GTNPORTAL:"require", "exports", "module"], function(require, exports, module)
{
});
require, exports, module are built-in AMD modules of RequireJS
define(["require", "exports", "module"],function(require,exports,module){ exports.add = function(a,b) { return a + b; }; });
define(["require", "exports", "module"], function(require,exports,module){ var add = require('math').add; exports.increment = function(val) { return add(val,1); }; });
<module> <name>math</name> <native-script>path_to_math.js</native-script> </module> <module> <name>increment</name> <native-script>path_to_increment.js</native-script> </module>
<div> <script type="text/javascript"> require(["require", "math", "increment"], function(require) { //Business code using math.js and increment.js var increment = require('increment').increment; alert(increment(100));//Expect to see 101 in alert message }); </script> </div>