RequireJS - CommonJS


Advertisements

Module format is defined by CommonJS. It is defined without providing an equal option of browsers to other JavaScript environments. Therefore, CommonJS specification recomends Transport formats and an asynchronous require. You can easily convert the traditional CommonJS module format to work with RequireJS. But, all modules will not convert to the new format. Some of the exceptions are listed below −

  • Modules with conditional code to do a require call.
  • Modules with circular dependencies.

Manual Conversion

CommonJS Modules can be converted manually to the RequireJS format by using the following syntax −

define(function(require, exports, module) {
   //place CommonJS module content here
});

Conversion Tool

CommonJS Modules can be converted to the RequireJS format by using the r.js project converter tool, which is built in r.js file. You should specify the path of the file to be converted and the output folder as shown below −

node r.js -convert path/to/commonjs/modules/ path/to/output

Setting Exported Value

Some of the systems in CommonJS, allow setting the exported value by assigning the exported value as module.exports But RequireJS, supports the easier way of returning the value from the function passed to define. The advantage of this is you do not need the exports and module function arguments, so you can leave them off the module definition as shown below −

define(function (require) {
   var name = require('name');

   //Define the module as exporting a function
   return function () {
      name.doSomething();
   };
});

Alternative Syntax

The alternative way to specify dependencies is via a dependency array argument define(). But, the order of the names in the dependency array should match the order of arguments passed to the definition function define() as shown below −

define(['name'], function (name) {
   
   return function () {
      name.doSomething();
   };
});

Loading Modules from CommonJS Packages

To know about the location and package attributes modules are loaded in CommonJS packages using RequireJS by setting up the RequireJS configuration.

Optimization Tool

Optimization tool is present in RequireJS which can combine the module definitions together into optimized bundles for browser delivery. It operates as a command-line tool so that you can use it as part of the code deployment.

Advertisements