Skip to content

How to document a CommonJS module (module.exports)

Lloyd Brookes edited this page Oct 13, 2016 · 3 revisions

Using module.exports

1. Say you have a CommonJS module you'd like to document.

function add (a, b) {
  return a + b
}

module.exports = add

2. Given that jsdoc2md only generates markdown for documented identifiers and modules, you must document each identifier you want to appear in output - including the module. Therefore, you must use @module at the top of file to document the module.

/**
 * A module for adding two values.
 * @module add-two-values
 */

/**
 * Add two values.
 */
function add (a, b) {
  return a + b
}

module.exports = add

3. Still, the add function above will be documented as an inner of the module - we want it to be documented as the exported value. So, we explicitly declare it as exported by marking it as an @alias of the module:

/**
 * A module for adding two values.
 * @module add-two-values
 */

/**
 * Add two values.
 * @alias module:add-two-values
 */
function add (a, b) {
  return a + b
}

module.exports = add

4. This file will now appear in jsdoc2md output. Without the @module tag it will not appear.

What not to do

1. Never document module.exports directly. It doesn't work. So, avoid this:

/**
 * Add two values.
 */
module.exports = function add (a, b) {
  return a + b
}

Using exports

1. Say your module exports variable, class or function identifiers:

/**
 * @module example
 */

/**
* @type {number}
*/
var one = 1

/**
 * A method
 */
function two () {}

exports.one = one
exports.two = two

2. As the two inner declarations have documentation, they are shown in the output (not the exports expressions, as they are not documented):


example

example~one : number

Kind: inner property of example

example~two()

A method

Kind: inner method of example


3. To correctly represent those inner declarations as the exported values, we need to set @alias tags:

/**
 * @module example
 */

/**
* @type {number}
* @alias module:example.one
*/
var one = 1

/**
 * @type {number}
 * @alias module:example.two
 */
var two = 2

exports.one = one
exports.two = two

4. Using the @static tag also works, and looks cleaner:

/**
 * @module example
 */

/**
* @type {number}
* @static
*/
var one = 1

/**
 * @type {number}
 * @static
 */
var two = 2

exports.one = one
exports.two = two

5. Now the output looks more realistic:


example

example.one : number

Kind: static property of example

example.two : number

Kind: static property of example


Clone this wiki locally