Differences between revisions 9 and 10
Revision 9 as of 2013-06-05 21:44:32
Size: 1856
Editor: 71
Comment: official docs link
Revision 10 as of 2018-12-19 23:59:35
Size: 0
Editor: JoanTouzet
Comment: Replaced by http://docs.couchdb.org/en/latest/query-servers.html#require
Deletions are marked like this. Additions are marked like this.
Line 1: Line 1:

## page was renamed from commonjs_modules
= CommonJS Modules =

See also the [[http://docs.couchdb.org/en/latest/query-servers.html#require|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).

{{{#!highlight JavaScript
   language: "javascript",
   whatever : {
     stringzone : "exports.string = 'plankton';",
     commonjs : {
       whynot : "exports.test = require('../stringzone')",
       upper : "exports.testing = require('./whynot').test.string.toUpperCase()"
   shows: {
     simple: "function() {return 'ok'};",
     requirey : "function() { var lib = require('whatever/commonjs/upper'); return lib.testing; };"
   views: {
     lib: {
       foo: "exports.bar = 42;"
     test: {
       map: "function(doc) { emit(doc._id, require('views/lib/foo').bar); }"
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: [[JavascriptPatternViewCommonJs|Javascript Pattern to share code between View Map function and other functions]]