CommonJS Modules

See also the official documentation for this topic.

As of the 1.1 release of CouchDB you can use CommonJS 1.0 modules in your map, show, list, update, and validation functions. Reduce functions can NOT use modules. When using CommonJS in map function you must place your CommonJS under the views/lib property in your Design Document (see below).

   1   {
   2    _id:"_design/test",
   3    language: "javascript",
   4    whatever : {
   5      stringzone : "exports.string = 'plankton';",
   6      commonjs : {
   7        whynot : "exports.test = require('../stringzone')",
   8        upper : "exports.testing = require('./whynot').test.string.toUpperCase()"
   9      }
  10    },
  11    shows: {
  12      simple: "function() {return 'ok'};",
  13      requirey : "function() { var lib = require('whatever/commonjs/upper'); return lib.testing; };"
  14    },
  15    views: {
  16      lib: { 
  17        foo: "exports.bar = 42;" 
  18      },
  19      test: { 
  20        map: "function(doc) { emit(doc._id, require('views/lib/foo').bar); }"
  21      }
  22    }
  23   }

Within a show function you can require CommonJS modules that are defined within object in your design document. The id you pass to require() is a / delimited list of property names to resolve the module string within the design document.

All imports are relative to the design document root unless they start with ./ or ../, these are referred to as "relative require" statements. Relative require statements only work within CommonJS modules they cannot be used directly inside your show, list, update and validation functions.

See also: Javascript Pattern to share code between View Map function and other functions

CommonJS_Modules (last edited 2013-06-05 21:44:32 by 71)