Skip to content
This repository was archived by the owner on Aug 8, 2023. It is now read-only.

Commit 78b4786

Browse files
author
Mike Nikles
authored
Merge pull request #96 from mobify/module-definition
Adds a snippet for our recommended best practice around creating modules in JS
2 parents 21e7294 + 8afb735 commit 78b4786

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

javascript/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,3 +531,36 @@ functionThatReturnsAPromise()
531531
// other code here!
532532
});
533533
```
534+
535+
## Module Definition
536+
537+
When building a module that can be consumed by a number of different sources, we prefer
538+
to use [Universal Module Definition (UMD)](https://github.com/umdjs/umd), so that the
539+
module will be compatible with AMD, CommonJS, or plain script inclusion.
540+
For modules that are not shared across projects, UMD is not required.
541+
542+
For example:
543+
544+
```
545+
(function(root, factory) {
546+
if (typeof define === 'function' && define.amd) {
547+
// AMD. Register as an anonymous module.
548+
define([], factory);
549+
} else if (typeof exports === 'object') {
550+
// Node. Does not work with strict CommonJS, but
551+
// only CommonJS-like environments that support module.exports,
552+
// like Node.
553+
module.exports = factory();
554+
} else {
555+
// Browser globals (root is window)
556+
root.LibFoo = factory();
557+
}
558+
}(this, function() {
559+
560+
var LibFoo = {};
561+
return LibFoo;
562+
}));
563+
```
564+
565+
If it's not intended to be used in multiple sources (for example if it's a project-specific
566+
utils file), please follow the module definition that the project follows.

0 commit comments

Comments
 (0)