Module


CommonJS Standard In Browser

After linking river.js in html,there are two Global functions will be occupied, one is define the other is main.

define function is for registting modules and waiting for invoked.

1 //module A
2 define('module.A',function(exports,require,module){
3   //exports module.A.sing Api
4   exports.sing = function(song){
5     console.log(song + 'is playing');
6   }
7 });

you also can use return to exports api

1 //module A
2 define('module.A',function(exports,require,module){
3   //exports module.A.sing Api
4   return {
5     sing : function(song){
6       console.log(song + 'is playing');
7     }
8   }
9 });

Dependence

1 //module B
2 define('module.B',function(exports,require,module){
3   //get module.A
4   var A = require('module.A');
5   //call sing api
6   A.sing('Heal the world');
7 });

you also can use this.need to handle dependence

1 //module A
2 define('module.A',function(exports,require,module){
3   //get module.A
4   var A = this.need('module.A');
5   //call sing api
6   A.sing('Heal the world');
7 });

main function is for registting a anonymous modules and will be executed immediately. It's the entrance of your programme ,this is influenced by other language's main keyword.

Most of time you don't need to use main function.you can simplly use scope markup in html insteadof it for executing modules. as It's easy to bind dom and data together.

1 //this anonymous module will be executed immediately
2 main(function(exports,require,module){
3   //run module.B
4   require('module.B');
5 });

return and this.need style also can be used in main function

Pre-build process

 1 //Module dependence
 2 var a = require('a')
 3   , b = require('b');
 4 
 5 //property
 6 var name='peter';
 7 exports.getName = function(){
 8   return name;
 9 }
10 exports.setName = function(value){
11   name = value;
12 }
     .                  .
     └── person.js =>   ├── build
                        │   ├── app.js
                        │   ├── river.js
                        │   └── river.min.js
                        ├── person.js
                        └── river.json
<script src="build/river.js">
<script src="build/app.js">

riverjs build tool will recursion the target foler to merge *.js into build/app.js, the module name is based on the folder structure you definded,for example if you have a module A with 5 level folder structure a/b/c/d/e/moduleA , then you can require('a.b.c.d.e.moduleA') to call it in any modules. another thing is that you can minify the build/app.js or add sourceMap support by changing river.json

{
  "version": "1.0.82",//current riverjs version
  "dist": "./build",  //default dist folder
  "alias": {
    "river.grammer": "grammar"
  },
  "sourcemap": false, //true, build with sourceMap
  "minify": false     //true, build with minified
}