Skip to Content
Learning JavaScript Design Patterns
book

Learning JavaScript Design Patterns

by Addy Osmani
July 2012
Intermediate to advanced
254 pages
6h 16m
English
O'Reilly Media, Inc.
Content preview from Learning JavaScript Design Patterns

CommonJS

The CommonJS module proposal specifies a simple API for declaring modules that work outside of the browser (such as on the server). Unlike AMD, it attempts to cover a broader set of concerns such as IO, filesystem, promises, and more.

Originally called ServerJS in a project started by Kevin Dangoor back in 2009, the format was more recently formalized by CommonJS, a volunteer working group that aims to design, prototype, and standardize JavaScript APIs. To date, they’ve attempted to ratify standards for both modules and packages.

Getting Started

From a structure perspective, a CommonJS module is a reusable piece of JavaScript that exports specific objects made available to any dependent code. Unlike AMD, there are typically no function wrappers around such modules (so we won’t see define here, for example).

CommonJS modules basically contain two primary parts: a free variable named exports, which contains the objects a module wishes to make available to other modules, and a require function that modules can use to import the exports of other modules (Examples 11-9, 11-10, and 11-11).

Example 11-9. Understanding CommonJS: require() and exports

// package/lib is a dependency we require
var lib = require( "package/lib" );

// behaviour for our module
function foo(){
    lib.log( "hello world!" );
}

// export (expose) foo to other modules
exports.foo = foo;

Example 11-10. Basic consumption of exports

// package/lib is a dependency we require
var lib = require( "package/lib" );

// behaviour ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Mastering JavaScript Design Patterns - Second Edition

Mastering JavaScript Design Patterns - Second Edition

Simon Timms
JavaScript Patterns

JavaScript Patterns

Stoyan Stefanov

Publisher Resources

ISBN: 9781449334840Errata Page