RequireJS - NodeJS


Advertisements


The Node adapter can be used along with the implementation of Require and Node's search path. If there is no module configuration used by RequireJS, you can use the existing Node based modules without changing them. You can install the node packages in the node_modules directory of project by using the npm command.

Node will load modules only from the local disk and config options such as map, packages, paths, etc. will be applied only when module is loaded by RequireJS.

Installing Node

You can install the Node adapter by using the following command which will install the latest release files −

npm install requirejs

You can install the Node in the following ways as well −

  • You can download the r.js from this link and keep it in your project folder.

  • Obtain the source from r.js repository or install it through node dist.js.

Usage of Node

To use the node, you need to have require('requirejs') and move the require function in the configuration to the top level main.js file.

For instance −

var requirejs = require('requirejs');

requirejs.config({
   //load the mode modules to top level JS file 
   //by passing the top level main.js require function to requirejs
   nodeRequire: require
});

requirejs(['name1', 'name2'],
   function (name1, name2) {
      //by using requirejs config, name1 and name2 are loaded
      //node's require loads the module, if they did not find these
   }
);

Building node modules with AMD or RequireJS

You can make code module work with RequireJS and Node, without requiring users of library, and then use the amdefine package to accomplish this work.

For instance −

if (typeof define !== 'function') {
   var define = require('amdefine')(module);
}

define(function(require) {
   var myval = require('dependency');

   //The returned value from the function can be used 
   //as module which is visible to Node.
   return function () {};
});

Optimizer as a Node Module

Node module uses the RequireJS optimizer as an optimize method by using the function call instead of using the command line tool.

For instance −

var requirejs = require('requirejs');

var config = {
   baseUrl: '../directory/scripts',
   name: 'main',
   out: '../build/main-built.js'
};

requirejs.optimize(config, function (buildResponse) {

   //The text output of the modules specify by using buildResponse 
   //and loads the built file for the contents
   //get the optimized file contents by using config.out 
   var contents = fs.readFileSync(config.out, 'utf8');
}, function(err) {
   //code for optimization err callback
});


Advertisements
E-Books Store