Coding Standard‐2 ESDoc - JUCSE49-Mavericks/Smart-Class-Routine-Management-System GitHub Wiki

Author: Jannati Tajrimin Mitu


Overview

ESDoc is an API documentation generator for JavaScript. It creates an HTML documentation site based on the comments added to the code. This documentation is useful for describing the API of a JavaScript application or library, allowing for easy reference and maintenance.

Adding Documentation Comments

To document JavaScript code using ESDoc, follow these steps:

Start with an ESDoc Comment Block: Documentation comments should be placed directly before the code they document. Each comment block starts with /** and ends with */.

/**
 * This is a description of the foo function.
 */
function foo() {
}

Use ESDoc Tags

Tags in ESDoc provide additional information about the code and its structure. Here are some commonly used tags:

  • @param {Type} name - Description: Describes a function parameter.
  • @returns {Type} Description: Describes the return value of a function.
  • @constructor: Indicates that a function is a constructor.
  • @namespace: Defines a namespace.
  • @module: Indicates a module.
  • @example: Provides usage examples.

Example with Tags:

/**
 * Represents a book.
 * @constructor
 * @param {string} title - The title of the book.
 * @param {string} author - The author of the book.
 */
function Book(title, author) {
}

Generating Documentation

After adding comments to your code, you can generate a documentation website using ESDoc.

Install ESDoc

If you haven’t already installed ESDoc, you can do so using npm:

npm install -g esdoc

Run the Documentation Generator

Use the command line to generate the documentation. Run the following command in your terminal, replacing book.js with the path to your JavaScript file:

esdoc

This command generates a docs directory in your current working directory containing the HTML documentation.

View the Documentation

Open the generated HTML files in the docs directory using a web browser to view your documentation.

Customizing Templates

By default, ESDoc uses a built-in template. You can customize this template or create a new one:

Edit Default Template

Modify the built-in template files located in the node_modules/esdoc/templates/default directory.

Create a New Template

Create a custom template by following the ESDoc template guidelines and set it in the ESDoc configuration file (esdoc.json).

Using Namepaths with ESDoc

Namepaths in ESDoc serve a similar purpose to uniquely identify and refer to different parts of your code, such as methods, properties, and nested functions. They help in disambiguating various members of classes, objects, and functions.

Basic Syntax

Here’s how to use namepaths in ESDoc:

  • Instance Members:
    MyConstructor#instanceMember

  • Static Members:
    MyConstructor.staticMember

  • Inner Members:
    MyConstructor~innerMember

Example

Consider the following example with a Person constructor, which includes an instance method, an inner function, and a static method:

/**
 * @constructor
 */
function Person() {
    this.say = function() {
        return "I'm an instance.";
    };

    function say() {
        return "I'm inner.";
    }
}

/**
 * @static
 */
Person.say = function() {
    return "I'm static.";
};

var p = new Person();
p.say();      // "I'm an instance."
Person.say(); // "I'm static."

To refer to these methods using namepaths:

  • Instance Method:
    Person#say

  • Static Method:
    Person.say

  • Inner Method:
    Person~say

The inner method say is not directly accessible from outside the function but can be referred to as Person~say. This can be useful if inner methods are exposed or returned through other means.

Chaining Namepaths

If you have nested constructors or members, you can chain the namepaths:

/**
 * @constructor
 */
function Person() {
    /**
     * @constructor
     */
    this.Idea = function() {
        this.consider = function() {
            return "hmmm";
        };
    };
}

var p = new Person();
var i = new p.Idea();
i.consider(); // "hmmm"

To refer to the consider method of the Idea constructor:
Person#Idea#consider

Special Cases

  • Modules:
    Use @module and prefix the name with module::.

    /** A module. Its name is module:foo/bar. */
  • Externals:
    Use @external and prefix the name with external::.

    /** The built-in string object. Its name is external:String. */
  • Events:
    Use @event and prefix the name with event::.

    /** An event. Its name is module:foo/bar.event:MyEvent. */

Objects with Special Characters

When dealing with objects or properties that have special characters in their names, use quotes around the names:

/** @namespace */
var chat = {
    /**
     * Refer to this by {@link chat."#channel"}.
     * @namespace
     */
    "#channel": {
        /**
         * Refer to this by {@link chat."#channel".open}.
         * @type {boolean}
         * @defaultvalue
         */
        open: true,
        /**
         * Internal quotes must be escaped with a backslash.
         * {@link chat."#channel"."say-\"hello\""}.
         */
        'say-"hello"': function(msg) {}
    }
};

/**
 * Define an event in our {@link chat."#channel"} namespace.
 * @event chat."#channel"."op:announce-motd"
 */

In this example, quotes and backslashes are used to handle special characters in names:

  • Namespace with Special Characters:
    chat."#channel"

  • Event with Special Characters:
    chat."#channel"."op:announce-motd"

Command-Line Arguments for ESDoc

ESDoc can be run with various command-line options to customize how documentation is generated. Here’s a breakdown of the available options and their usage:

Basic Usage

To generate documentation, run ESDoc with the path to the source code files:

esdoc -c esdoc.json

You can also include a README file to add content to the documentation's front page.

Command-Line Options

  • -c, --config
    Description: Path to the ESDoc configuration file. This file is used to customize documentation generation.

  • -o , --output
    Description: Path to the output folder for generated documentation. Defaults to docs.

  • --dry-run
    Description: Perform a dry run of the documentation generation without creating any files.

  • -v, --version
    Description: Display ESDoc's version number and exit.

  • -h, --help
    Description: Display help information about command-line options.

  • --debug
    Description: Enable logging for debugging ESDoc issues.

  • --verbose
    Description: Log detailed information during execution.

  • --exclude
    Description: Exclude files matching the specified pattern from the documentation generation.

Examples

  1. Generate Documentation with Configuration File:

    esdoc -c /path/to/my/esdoc.json -o docs
  2. Run ESDoc with Debugging Information:

    esdoc --debug
  3. Generate Documentation Excluding Certain Files:

    esdoc -c esdoc.json --exclude "*.test.js"

By using these options, you can tailor ESDoc's output and behavior to better fit your project's needs.

Configuring ESDoc with a Configuration File

Configuration File Formats

JSON File
This format is straightforward and does not allow comments.
Example:

{
    "plugins": ["esdoc-plugins-markdown"]
}

CommonJS Module
This format is a JavaScript file that exports a configuration object.
Example:

'use strict';

module.exports = {
    plugins: ['esdoc-plugins-markdown']
};

Running ESDoc with a Configuration File

Use the -c command-line option to specify the configuration file:

esdoc -c /path/to/esdoc.json

Default Configuration Options

If no configuration file is provided, ESDoc uses default settings similar to the following:

{
    "source": "./src",
    "destination": "./docs",
    "includes": [],
    "excludes": [],
    "plugins": [],
    "title": "Your Project Title",
    "version": "1.0.0"
}
  • Source: Defaults to the src directory.
  • Destination: Defaults to the docs directory.
  • Plugins: No plugins are loaded.

Configuring Plugins

To enable plugins, list their paths in the plugins array:

{
    "plugins": [
        "esdoc-plugins-markdown",
        "esdoc-plugins-summary"
    ]
}

Specifying Input Files

Use includes and excludes to specify files and directories:

{
    "includes": ["path/to/files"],
    "excludes": ["path/to/ignore"]
}

Incorporating Command-Line Options

Include command-line options in the opts section:

{
    "opts": {
        "output": "./docs",
        "encoding": "utf8",
        "recurse": true
    }
}

Configuring Tags

Adjust tag handling with the tags options:

{
    "tags": {
        "allowUnknownTags": true
    }
}

Configuring Templates

Customize the appearance of the generated documentation:

{
    "templates": {
        "cleverLinks": true,
        "monospaceLinks": true
    }
}
  • cleverLinks: If true, inline links are rendered based on their type.
  • monospaceLinks: If true, all links are rendered in monospace.

For more advanced configurations, refer to the ESDoc documentation and community plugins for additional options and examples.

Configuring ESDoc's Default Template

1. Generating Pretty-Printed Source Files

By default, ESDoc generates pretty-printed versions of your source files. To disable this feature, set:

{
  "templates": {
    "default": {
      "outputSourceFiles": false
    }
  }
}

2. Copying Static Files to the Output Directory

To copy additional static files (like images or stylesheets) to the output directory, you can define the following:

  • Include static files: Define paths whose contents should be copied.
  • Exclude static files: Define paths that should be excluded.
  • Include files by pattern: Use a regex pattern to include files.
  • Exclude files by pattern: Use a regex pattern to exclude files.

Example configuration to copy a directory of images:

{
  "templates": {
    "default": {
      "staticFiles": {
        "include": [
          "./myproject/static"
        ]
      }
    }
  }
}

3. Showing the Current Date in the Page Footer

To omit the current date from the footer, set:

{
  "templates": {
    "default": {
      "includeDate": false
    }
  }
}

4. Showing Longnames in the Navigation Column

To display the full longname of symbols in the navigation column instead of a shortened version, set:

{
  "templates": {
    "default": {
      "useLongnameInNav": true
    }
  }
}

5. Overriding the Default Template’s Layout File

To use your own layout file, specify the path to the custom layout file:

{
  "templates": {
    "default": {
      "layoutFile": "./path/to/your/layout.tmpl"
    }
  }
}

Example Configuration File

Here's an example configuration file that incorporates all the above customizations:

{
  "templates": {
    "default": {
      "outputSourceFiles": false,
      "staticFiles": {
        "include": [
          "./myproject/static"
        ],
        "excludePattern": ".*\\.ignore$"
      },
      "includeDate": false,
      "useLongnameInNav": true,
      "layoutFile": "./custom/layout.tmpl"
    }
  }
}

To use this configuration, save it as a JSON file (e.g., conf.json) and run ESDoc with the -c option:

esdoc -c /path/to/conf.json

This will apply the specified customizations to your ESDoc documentation.

Block and Inline Tags in ESDoc

Block Tags

Block tags provide detailed information about the code and are placed at the top level of a comment. Each block tag must be followed by a line break, except for the last block tag. Examples include:

  • @param: Describes a function parameter.
  • @returns or @return: Describes the return value of a function.
  • @typedef: Defines a custom type.
  • @example: Provides an example of how to use a function or method.

Example:

/**
 * Set the shoe's color.
 *
 * @param {string} color - The shoe's color.
 * @returns {void}
 */
Shoe.prototype.setColor = function(color) {
    // ...
};

Inline Tags

Inline tags are used within the text of a block tag or description, enclosed in curly braces. They help link to other parts of the documentation.

Example:

/**
 * Set the shoe's color. Use {@link Shoe#setSize} to set the shoe size.
 *
 * @param {string} color - The shoe's color.
 */
Shoe.prototype.setColor = function(color) {
    // ...
};

Combining Block and Inline Tags

You can use inline tags within block tags or descriptions for referencing.

Example:

/**
 * Set the shoe's color.
 *
 * @param {SHOE_COLORS} color - The shoe color. Must be an enumerated
 * value of {@link SHOE_COLORS}.
 */
Shoe.prototype.setColor = function(color) {
    // ...
};

Multiple Block Tags

When using multiple block tags in a comment, ensure they are separated by line breaks.

Example:

/**
 * Set the color and type of the shoelaces.
 *
 * @param {LACE_COLORS} color - The shoelace color.
 * @param {LACE_TYPES} type - The type of shoelace.
 */
Shoe.prototype.setLaceType = function(color, type) {
    // ...
};

By using these guidelines, you can effectively document your JavaScript code with ESDoc, making it easier for others to understand and use your API.


ESDoc Plugins: Overview and Creation

Creating and Enabling a Plugin

To create and enable an ESDoc plugin, follow these two main steps:

  1. Create a JavaScript Module: Write your plugin code in a JavaScript module. This module should export the necessary functions and objects that ESDoc will utilize.

  2. Configure ESDoc: Add the path to your plugin module in the plugins array of ESDoc's configuration file. You can specify either an absolute or relative path. For example, if your plugin is located in plugins/myPlugin.js, configure it as follows:

    {
        "plugins": ["plugins/myPlugin"]
    }

Authoring ESDoc Plugins

ESDoc's plugin system allows for extensive control over the documentation generation process. Here’s how to utilize different features:

Event Handlers

Plugins can register handlers for specific events. Here's an example of how to handle the newDoclet event:

exports.onNewDoclet = function(doclet) {
    // Handle the creation of a new doclet
};

Common Events:

  • parseStart: Triggered before ESDoc starts parsing source files.
  • fileStart: Triggered before parsing each file. Useful for file-specific initialization.
  • jsdocCommentFound: Triggered when a JSDoc comment is found, allowing modification of comment content.
  • newDoclet: Fired when a new doclet is created, allowing modifications.
  • parseEnd: Triggered after all source files are parsed.
Tag Definitions

Plugins can define new tags or modify existing ones. Here’s an example:

exports.defineTags = function(dictionary) {
    dictionary.defineTag('myTag', {
        onTagged: function(doclet, tag) {
            doclet.myCustomProperty = tag.value;
        }
    });
};
Reporting Errors

If your plugin needs to report errors, use the built-in logging methods:

const logger = require('esdoc/util/logger');

exports.onNewDoclet = function(doclet) {
    if (someErrorCondition) {
        logger.error('An error occurred!');
    }
};

Using the Markdown Plugin

Overview

ESDoc includes a Markdown plugin that converts Markdown-formatted text to HTML. This plugin is available in ESDoc versions 0.6.0 and later.

Important Note: Ensure each line of your JSDoc comments begins with a leading asterisk (*) for proper Markdown formatting.

Enabling the Markdown Plugin

To enable the Markdown plugin, add esdoc-plugin-markdown to the plugins array in your ESDoc configuration file. Example configuration:

{
    "plugins": ["esdoc-plugin-markdown"]
}

Configuring Markdown Processing

  • Custom Tags: To include Markdown processing in additional tags, use:

    {
        "plugins": ["esdoc-plugin-markdown"],
        "markdown": {
            "tags": ["myTag"]
        }
    }
  • Excluding Tags: To prevent certain tags from being processed:

    {
        "plugins": ["esdoc-plugin-markdown"],
        "markdown": {
            "excludeTags": ["author"]
        }
    }
  • Hard-Wrapping Text: To enable hard-wrapping, set:

    {
        "plugins": ["esdoc-plugin-markdown"],
        "markdown": {
            "hardwrap": true
        }
    }
  • Adding IDs to Headings: To add id attributes to headings automatically:

    {
        "plugins": ["esdoc-plugin-markdown"],
        "markdown": {
            "idInHeadings": true
        }
    }

Example Configuration File

Here’s an example configuration file incorporating all the above customizations:

{
    "plugins": ["esdoc-plugin-markdown"],
    "markdown": {
        "tags": ["foo", "bar"],
        "excludeTags": ["author"],
        "hardwrap": true,
        "idInHeadings": true
    }
}

To use this configuration, save it as a JSON file (e.g., esdoc.json) and run ESDoc with the specified configuration:

esdoc -c /path/to/esdoc.json

This will apply the specified customizations to your ESDoc documentation.


Tutorials in ESDoc

ESDoc allows you to include detailed tutorials alongside your API documentation, making it useful for providing guides, "getting started" instructions, or step-by-step processes for implementing features.

Adding Tutorials

To include tutorials in your ESDoc documentation, use the --tutorials or -u option when running ESDoc, specifying the directory containing your tutorial files. For example:

esdoc -u path/to/tutorials path/to/js/files

ESDoc will search for tutorial files with the following extensions:

  • .htm
  • .html
  • .markdown (converted from Markdown to HTML)
  • .md (converted from Markdown to HTML)
  • .xhtml
  • .xml (treated as HTML)

Configuring Titles, Order, and Hierarchy

By default, ESDoc uses the filename as the title for each tutorial, and all tutorials are treated as being at the same level. You can customize this using a JSON file to define titles, order, and hierarchy.

JSON File Formats
  1. Tree of Objects Format

    Create a JSON file where each tutorial can have a children property that lists its sub-tutorials. For example:

    {
        "tutorial1": {
            "title": "Tutorial One",
            "children": {
                "childA": {
                    "title": "Child A"
                },
                "childB": {
                    "title": "Child B"
                }
            }
        },
        "tutorial2": {
            "title": "Tutorial Two"
        }
    }
  2. Top-Level Object Format

    Use a JSON file where each property is a tutorial object. List child tutorials by name in the children array. For example:

    {
        "tutorial1": {
            "title": "Tutorial One",
            "children": ["childA", "childB"]
        },
        "tutorial2": {
            "title": "Tutorial Two"
        },
        "childA": {
            "title": "Child A"
        },
        "childB": {
            "title": "Child B"
        }
    }

    Note: Providing individual .json files for each tutorial is deprecated and not recommended for new projects.

Linking to Tutorials from API Documentation

You can link to tutorials from your API documentation in two primary ways:

  1. @tutorial Block Tag

    Use the @tutorial block tag in an ESDoc comment to include a link to the tutorial. For example:

    /**
     * Class representing a socket connection.
     *
     * @class
     * @tutorial socket-tutorial
     */
    function Socket() {}
  2. {@tutorial} Inline Tag

    Use the {@tutorial} inline tag within another ESDoc tag to link to a tutorial. By default, ESDoc will use the tutorial’s title as the link text. For example:

    /**
     * Class representing a socket connection. See {@tutorial socket-tutorial}
     * for an overview.
     *
     * @class
     */
    function Socket() {}

Including a Package File in ESDoc Documentation

Incorporating information from your project's package.json file into ESDoc documentation is useful for displaying details like the project's name and version number. ESDoc can automatically use this information when generating documentation.

Methods to Include a Package File

  1. Including the Package File in Source Paths

    Add the path to your package.json file alongside your JavaScript files when running ESDoc. ESDoc will use the first package.json file it finds in the specified source paths.

    Example:

    esdoc -f path/to/js path/to/package/package.json
  2. Using the -P/--package Command-Line Option

    Specify the path to your package.json file using the -P or --package command-line option. This method overrides the package files found in your source paths.

    Example:

    esdoc -P path/to/package/package.json path/to/js

Notes:

  • The package.json file must follow npm's package format to be correctly processed by ESDoc.
  • The -P/--package option takes precedence over any package.json files found in your source paths. If you use this option, ESDoc will ignore other package.json files that might be in the source paths.

By using these methods, you ensure that your project's metadata is accurately reflected in the generated documentation, providing clear and useful information about the project.


Including a README File in ESDoc Documentation

Including a README file in your ESDoc documentation can be a great way to provide an overview or additional information about your project. ESDoc can integrate content from a README file into the generated documentation.

Methods to Include a README File

  1. Including the README File in Source Paths

    Specify the path to a README file (e.g., README.md) alongside your JavaScript files when running ESDoc. ESDoc will use the first README file it finds in the specified source paths.

    Example:

    esdoc -f path/to/js path/to/readme/README.md
  2. Using the -R/--readme Command-Line Option

    Use the -R or --readme command-line option to specify the path to your README file. This method allows the README file to have any name and extension, as long as it is in Markdown format. This option takes precedence over any README files found in your source paths.

    Example:

    esdoc -R path/to/readme/README.md path/to/js

Notes:

  • When using ESDoc's default template, the contents of the README file will be rendered in HTML and included in the generated documentation.
  • The -R/--readme option allows for greater flexibility in naming and locating the README file compared to relying on it being named README.md and located in the source paths.

By including a README file, you enhance the documentation with important context and information about your project, making it more accessible and informative for users and developers.


Reference Section for ESDoc

Official Documentation and Resources:

Additional Resources:


⚠️ **GitHub.com Fallback** ⚠️